import objectdraw.*;

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

import java.io.*;

import javax.swing.*;

/*
 * A simple Text Editor.  It has two features: it can
 * load a file and it can save a file.
 */
//@width 800
//@height 600
public class CountWords extends Controller implements ActionListener {
  private JButton loadButton;
  private JButton countButton;
  private JTextArea textArea;
  private JLabel count;
  private JTextField wordField;

  public static void main(String args[]) {
    new CountWords().startController();
  }

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

    JPanel p = new JPanel();
    loadButton = new JButton("Load File");
    p.add(loadButton);

    countButton = new JButton("Count");
    p.add(countButton);

    p.add(new JLabel("Word: "));
    wordField = new JTextField(12);
    p.add(wordField);

    p.add(count = new JLabel("Count: 0"));

    textArea = new JTextArea("Note: Load File will not work if running in a browser");
    textArea.setFont(new Font("Times", Font.PLAIN, 24));
    getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
    getContentPane().add(p, BorderLayout.NORTH);

    loadButton.addActionListener(this);
    countButton.addActionListener(this);

    validate();
  }

  private int countWords(String text, String word) {
    int count = 0;
    int pos = text.indexOf(word, 0);

    while (pos > -1) {
      count++;
      pos = text.indexOf(word, pos + word.length());
    }

    return count;
  }

  // Listener for button clicks that loads the
  // specified web pages and puts it in the
  // browser component.
  public void actionPerformed(ActionEvent event) {
    if (event.getSource() == loadButton) {
      loadFile();
    } else {
      String text = textArea.getText();
      String word = wordField.getText();
      int num = countWords(text, word);
      count.setText("Count: " + num);
    }
  }

  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);
      }
    }
  }
}
