/**
 * A substitution cipher that encrypts text by replacing each letter with the
 * corresponding letter from a 26-character key alphabet.
 */
public class SubstitutionCipher extends Cipher {

    /** A permutation of the 26 uppercase letters used as the substitution key. */
    private String keyAlphabet;

    /**
     * Constructs a SubstitutionCipher with the given text and key alphabet.
     *
     * @param text        the input text
     * @param keyAlphabet a 26-character permutation of the alphabet (e.g. "QWERTYUIOPASDFGHJKLZXCVBNM")
     */
    public SubstitutionCipher(String text, String keyAlphabet) {
        super(text);
        this.keyAlphabet = keyAlphabet;
    }

    /**
     * Encrypt the text using substitution cipher with stored key
     *
     * @return the encrypted text
     */
    @Override
    public String encrypt() {
        String text = getText();
        String ret = "";
        for(int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            char encodedC = keyAlphabet.charAt( charToIndex(c)  );
            ret += encodedC;
        }
        return ret;
    }

    /**
     * Decrypt the text using substitution cipher with stored key
     *
     * @return the decrypted text
     */
    @Override
    public String decrypt() {
        String text = getText();
        String ret = "";
        for(int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            char decodedC = indexToChar(keyAlphabet.indexOf(c));
            ret += decodedC;
        }
        return ret;
    }
}
