import objectdraw.*;

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

import java.io.*;

import javax.swing.*;


//@width 800
//@height 550
public class Palindrome extends Controller implements ActionListener {
    private JButton loadButton;
    private JButton checkButton;
    private JTextArea textArea;
    private JLabel answer;

    public void begin() {
        this.resize(800, 600);

        JPanel p = new JPanel();

        checkButton = new JButton("Check Palindrome");
        p.add(checkButton);

        p.add(answer = new JLabel("???"));
        
        textArea = new JTextArea("level");
        textArea.setFont(new Font("Times", Font.PLAIN, 24));
        getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
        getContentPane().add(p, BorderLayout.NORTH);

        checkButton.addActionListener(this);

        validate();
    }

    
    
    private boolean isPalindrome(String text) {
       for (int i = 0; i < text.length() / 2; i++) {
           if (text.charAt(i) != text.charAt(text.length() - i - 1)){
               return false;
            }
        }
        return true;
    }


    
    private boolean isPalindrome2(String text) {
        if (text.length() < 2) {
            return true;
        } else {
            return text.charAt(0) == text.charAt(text.length() - 1) &&
                   isPalindrome2(text.substring(1, text.length() - 1));
        }
        
    }

    
    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == loadButton) {
            loadFile();
        } else {
            String text = textArea.getText();
            if (isPalindrome(text)) {
                answer.setText("YES!");
            } else {
                answer.setText("NO!");
            }
        }
    }

    private void loadFile() {
        textArea.setText(""); // clear window

        JFileChooser chooser = new JFileChooser();

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

            try {
                // read in the file, appending each line
                // to the text window
                BufferedReader input = new BufferedReader(new FileReader(file));

                String line = input.readLine();

                while (line != null) {
                    textArea.append(line + "\n");
                    line = input.readLine();
                }

                input.close();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Error: " + e);
            }
        }
    }
}
