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

/*
 * Search and Replace example
 */
//@width 800
//@height 550
public class SearchReplace extends Controller implements ActionListener {

  private JButton loadButton, replaceButton;
  private JTextArea text;

  private JTextField search;
  private JTextField replace;    

  public void begin() {

    this.resize(800,600);

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

    replaceButton = new JButton("Search and Replace");
    p.add(replaceButton);

    p.add(new JLabel("Search: "));
    search = new JTextField(12);
    p.add(search);
    p.add(new JLabel("Replace: "));
    replace = new JTextField(12);
    p.add(replace);

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

    loadButton.addActionListener(this);
    replaceButton.addActionListener(this);

    validate();
  }


  // 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 {
      text.setText(searchAndReplace(search.getText(), 
          replace.getText(), 
          text.getText()));
    } 
  }

  
  
  /**
   * Replace all occurrences of 'search' with 'replace' in text.  
   * 
   * Note:  This version finds an occurrence, replaces it, and then starts 
   * over from the beginning.
   */
  private String searchAndReplace(String search, String replace, String text) {
    // find first occurence of search string
    int pos = text.indexOf(search);

    while (pos > -1) {

      text = text.substring(0, pos) + replace + text.substring(pos + search.length());

      // start from end of replacement (in case replacement contains
      // the search string...
      pos = text.indexOf(search, pos + replace.length());

    }

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

