/**
 * A Vigenere cipher that encrypts text by shifting each character by the
 * corresponding letter of a repeating keyword. A generalization of the
 * Caesar cipher: a single-character keyword is equivalent to Caesar.
 */
public class VigenereCipher extends CaesarCipher {

    /** The keyword whose letters determine the per-character shift amounts. */
    private String keyword;

    /**
     * Constructs a VigenereCipher with the given text and keyword.
     *
     * @param text    the input text
     * @param keyword the encryption keyword (will clean before storing it)
     */
    public VigenereCipher(String text, String keyword) {
        super(text, 0);
        this.keyword = keyword;
    }

    /**
     * Encrypt the text using Vigenere cipher
     *
     * @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);
            int shift =  charToIndex(keyword.charAt(i % keyword.length())); 
            char encC = shiftChar(c, shift);
            ret += encC;
        }
        return ret;
        
    }

    /**
     * Decrypt the text using Vigenere cipher
     *
     * @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);
            int shift =  charToIndex(keyword.charAt(i % keyword.length())); 
            char decC = shiftChar(c, -shift);
            ret += decC;
        }
        return ret;
        
    }
}
