import objectdraw.*;

import java.awt.*;
import java.awt.event.*;

import java.io.*;

import javax.swing.*;


public class Decrypt extends Controller implements ActionListener {
    private JTextArea original;
    private JTextArea decrypted;
    private JButton chooseFile;

    public void begin() {
        original = new JTextArea();
        decrypted = new JTextArea();

        Container content = getContentPane();
        JPanel p = new JPanel();
        p.setLayout(new GridLayout(2, 1));

        JScrollPane sp = new JScrollPane(original);
        sp.setBorder(BorderFactory.createTitledBorder("Original"));
        p.add(sp);

        sp = new JScrollPane(decrypted);
        sp.setBorder(BorderFactory.createTitledBorder("Decrypted"));
        p.add(sp);

        content.add(p, BorderLayout.CENTER);

        chooseFile = new JButton("Load File");
        chooseFile.addActionListener(this);
        p = new JPanel();
        p.add(chooseFile);
        content.add(p, BorderLayout.SOUTH);
        validate();
    }

    /*
     * Rotate each lowercase alphabet char by one letter
     * to the "left" in the alphabet.
     *
     * How would you change this method to rotate by
     * 3 or more characters? (Hint: modular arithmetic)
     */
    private char decryptChar(char ch) {
        if (('a' <= ch) && (ch <= 'z')) {
            if (ch == 'a') {
                return 'z';
            } else {
                return (char) (ch - 1);
            }
        } else {
            return ch;
        }
    }

    /*
    * Decrypt each character on a line
     */
    public String decryptLine(String line) {
        String result = "";
        line = line.toLowerCase();

        for (int i = 0; i < line.length(); i++) {
            result = result + decryptChar(line.charAt(i));
        }

        return result;
    }

    private void loadFile() {
        JFileChooser chooser = new JFileChooser();

        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();

            try {
                // open the file chosen by the user
                BufferedReader in = new BufferedReader(new FileReader(file));

                String line = in.readLine();

                while (line != null) {
                    original.append(line + "\n");
                    decrypted.append(decryptLine(line) + "\n");
                    line = in.readLine();
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Error: " + e);
            }
        }
    }

    public void actionPerformed(ActionEvent event) {
        original.setText("");
        decrypted.setText("");
        loadFile();
    }
}
