/**
 * A Caesar cipher that encrypts text by shifting each character a fixed
 * number of positions forward in the alphabet.
 */
public class CaesarCipher extends Cipher {

    /** The number of positions to shift each character. */
    protected int shift;

    /**
     * Constructs a CaesarCipher with the given text and shift amount.
     *
     * @param text  the input text
     * @param shift the number of positions to shift
     */
    public CaesarCipher(String text, int shift) {
       super(text); 
       this.shift = shift;
    }

    /**
     * Shifts a single uppercase letter by the given amount (mod 26).
     * Handles negative amounts correctly.
     *
     * @param c      an uppercase letter
     * @param amount the shift amount (may be negative)
     * @return the shifted letter
     */
    protected char shiftChar(char c, int amount) {
        int ret = charToIndex(c) + (amount % 26);
        if(ret < 0) {
            ret += 26;
        }
        return indexToChar(ret % 26);
    }

    /**
     * Encrypt the text using Caesar 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);
            char encodedC = shiftChar(c, shift);
            ret += encodedC;
        }
        return ret;
    }


    /**
     * Decrypt the text using Caesar 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);
            char decodedC = shiftChar(c, -shift);
            ret += decodedC;
        }
        return ret;
        
    }
}
