import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import objectdraw.*;

/*
 * A simple Text Editor.  It has two features: it can
 * load a file and it can save a file.
 */
public class TextEditor extends Controller implements ActionListener {

  private JButton saveButton, loadButton;
  private JTextArea text;

  public void begin() {
    JPanel p = new JPanel();
    saveButton = new JButton("Save File");
    loadButton = new JButton("Load File");
    p.add(saveButton);
    p.add(loadButton);

    text = new JTextArea();
    text.setFont(new Font("Times", Font.PLAIN, 18));
    getContentPane().add(new JScrollPane(text), BorderLayout.CENTER);
    getContentPane().add(p, BorderLayout.NORTH);

    saveButton.addActionListener(this);
    loadButton.addActionListener(this);

    validate();

    text.setText("Loading files may not work in Web Browser...");

  }

  // 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() == saveButton) {
      saveFile();
    } else {
      loadFile();
    }
  }

  private void saveFile() {

    JFileChooser chooser = new JFileChooser();
    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
      File file = chooser.getSelectedFile();
      try {

        // write the entire text of the text area to
        // to the file
        PrintWriter out = new PrintWriter(new FileWriter(file));

        out.println(text.getText());

        out.close();

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

  private void loadFile() {
    text.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) {
          text.append(line + "\n");
          line = input.readLine();
        }

        input.close();

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

