/* ---------------------------------------------------------------
 File:                           Draw.java
 Package:                        FSM Analyzer 2.0
 Author:                         Dr. Ratnesh Kumar and Greg Stamp
 V2.0 10/28/2006
 Initial Developers: Bharath Oruganti
 ---------------------------------------------------------------*/
 
/*
 * Dr. Ratnesh Kumar, Greg Stamp.
 * Department of Electrical and Computer Engineering
 * Iowa State University
 * October, 2006.
 *
 * Copyright (c) 2006
 * All rights reserved.
 */

package mainAnalyzer;


import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;


// **********************************
// * This class provides the Applet
// **********************************
public class Draw extends Applet {
    
	// Data members
	static final long serialVersionUID = 1L;
	static DrawFrame appFrame = null;
    Toolkit   toolKit = Toolkit.getDefaultToolkit();
    public TextArea  taText;
    public Frame parent;
    boolean FileState = true;
    Label     statusBar;

    String OPER;
    static String MI_NEW = "New",
            MI_OPEN = "Open...",
            MI_DRA = "Draw",
            MI_SAVE = "Save",
            MI_SAVEAS = "Save As...",
            MI_CRT = "Create Text",
            MI_CLOSE = "Close",

            DEF_FNAME = "Courier",
            DEF_FSIZE = "12",
            NEW_FILE = "untitled.txt";

    StringBuffer currFile = null;
    boolean inAnApplet = true, Edited = false, showStatusMsgInBrowser = true;
    Panel topPanel, buttonPanel;

    public void init() {
        setBackground(Color.lightGray);
 
        ButtonListener btListener = new ButtonListener();

        // Initialize variables
        currFile = new StringBuffer(NEW_FILE);

        // Push Button Tool Bar
        buttonPanel = new Panel();
        buttonPanel.setFont(new Font("Helvetica", Font.BOLD, 14));
        buttonPanel.setLayout(new GridLayout(1, 40));
        Button BtNew, BtOpen, BtDraw, BtSave, BtSaveas, BtCrt, BtClose;

        buttonPanel.add(BtNew = new Button(MI_NEW));
        buttonPanel.add(BtOpen = new Button(MI_OPEN));
        buttonPanel.add(BtDraw = new Button(MI_DRA));
        buttonPanel.add(BtSave = new Button(MI_SAVE));
        buttonPanel.add(BtSaveas = new Button(MI_SAVEAS));
        buttonPanel.add(BtCrt = new Button(MI_CRT));
        buttonPanel.add(BtClose = new Button(MI_CLOSE));
        BtNew.addActionListener(btListener);
        BtOpen.addActionListener(btListener);
        BtDraw.addActionListener(btListener);
        BtSave.addActionListener(btListener);
        BtSaveas.addActionListener(btListener);
        BtCrt.addActionListener(btListener);
        BtClose.addActionListener(btListener);

        // Top of screen panel
        topPanel = new Panel();
        topPanel.setLayout(new BorderLayout(1, 2));
        topPanel.add("Center", buttonPanel);

        // Text Editing Area (20 rows x 80 cols)
        taText = new TextArea(34, 5);
        taText.setBackground(Color.black);

        // Status Bar
        statusBar = new Label(NEW_FILE, Label.LEFT);

        // Add Panels to Applet (a Panel itself)
        setLayout(new BorderLayout(1, 2));
        add("North", topPanel);
        add("Center", taText);
        super.enableEvents(AWTEvent.WINDOW_EVENT_MASK | AWTEvent.KEY_EVENT_MASK);
     
    }

    // Set padding for fill3DRect() in paint()
    public Insets getInsets() {
        return new Insets(4, 4, 4, 4);
    }

    public void paint(Graphics g) {
        // Draw a 3D line below menu bar
        if (!inAnApplet) {
            g.setColor(getBackground());
            g.fill3DRect(0, 0, getSize().width, 2, false);
        } else {
            g.draw3DRect(0, 0, getSize().width - 1, getSize().height - 1, false);
        }
   
        // Always set cursor in text area
        taText.requestFocus();
    }

    public void callProcessEvent(AWTEvent evt) {
        processEvent(evt);
    }

    protected void processEvent(AWTEvent evt) {
        if (evt.getID() == Event.WINDOW_DESTROY) {
            // terminate(0);
            parent.dispose();
        } else if (evt.getSource() instanceof TextArea) {
            if (evt.getID() == Event.KEY_PRESS) {
                Edited = true;
            }
        }
    }

    protected void newFile() {
        saveWarning();
        // Clear screen for new file
        taText.setText("");
        currFile.setLength(0);
        FileState = true;
        currFile.append(NEW_FILE);
        statusMsg(NEW_FILE);
    }

    // Read a local file
    protected void readFile(String filename) {
        saveWarning();

        statusMsg("Please wait...");
        try {
            new ReadFile(filename, taText);
            currFile.setLength(0);
            currFile.append(filename);
            statusMsg(currFile.toString());
        } catch (FileNotFoundException e) {
            showCatchError(e);
        } catch (IOException e) {
            showCatchError(e);
        } finally {
            statusMsg("");
        }
    }

    // Write to local file
    protected void writeFile(String filename) {
        statusMsg("Please wait...");
        try {  
            new WriteFile(filename, taText);
            currFile.setLength(0);
            currFile.append(filename);
            statusMsg(currFile.toString());
            Edited = false;
        } catch (IOException e) {
            showCatchError(e);
        } finally {
            statusMsg("");
        }
    }

    protected void statusMsg(String msgText) {
        statusBar.setText(msgText);
        if (inAnApplet && showStatusMsgInBrowser) {
            showStatus(msgText);
        }
    }
   
    protected void showCatchError(Throwable e) {
        statusMsg(e.toString());
        if (inAnApplet) {
            showStatus(e.getMessage());
        } else {
            System.err.println(e.getMessage());
        }
    }

    protected void saveWarning() {
        if (Edited == true) {
            ;
        }  // Add warning message here later
        Edited = false;
    }

    protected void terminate(int rc) {
        saveWarning();
        System.exit(rc);
    }

    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent evt) {

            statusMsg("");

            // Button or Menu item selected
            if (evt.getSource() instanceof Button) {
                String  buttonLabel = evt.getActionCommand();

                if (buttonLabel.equals(MI_OPEN)) {
                    saveWarning();
                    DoFileDialog fd;

                    try {
                        if (inAnApplet) {
                            setEnabled(false); // Simulate modality
                            fd = new DoFileDialog(null, "Open a File");
                        } else {
                            fd = new DoFileDialog(appFrame, "Open a File");
                        }

                        if (fd.getPath() != null) {
                            readFile(fd.getPath());
                        }
                    } catch (AWTError e) {
                        showCatchError(e);
                        if (inAnApplet) {
                            statusMsg(
                                    e.toString()
                                            + "  (probably due to security restrictions)");
                        }
                    } finally {
                        if (inAnApplet) {
                            setEnabled(true);
                        }
                    }
                } else if (buttonLabel.equals(MI_SAVEAS)) {
                    saveWarning();
                    DoFileDialog fd;

                    try {
                        if (inAnApplet) {
                            setEnabled(false); // Simulate modality
                            fd = new DoFileDialog(null, "Save File As",
                                    FileDialog.SAVE);
                        } else {
                            fd = new DoFileDialog(appFrame, "Save File As",
                                    FileDialog.SAVE);
                        }
                        if (fd.getPath() != null) {
                            writeFile(fd.getPath());
                        }
                    } catch (AWTError e) {
                        showCatchError(e);
                        if (inAnApplet) {
                            statusMsg(
                                    e.toString()
                                            + "  (probably due to security restrictions)");
                        }
                    } finally {
                        if (inAnApplet) {
                            setEnabled(true);
                        }
                    }
                } else if (buttonLabel.equals(MI_CLOSE)) {
                    parent.setVisible(false);
                    parent.dispose();
                } else if (buttonLabel.equals(MI_SAVE)) {
                    if (FileState == true) {
                        saveWarning();
                        DoFileDialog fd;
 
                        try {
                            if (inAnApplet) {
                                setEnabled(false); // Simulate modality
                                fd = new DoFileDialog(null, "Save File As",
                                        FileDialog.SAVE);
                            } else {
                                fd = new DoFileDialog(appFrame, "Save File As",
                                        FileDialog.SAVE);
                            }
                            if (fd.getPath() != null) {
                                writeFile(fd.getPath());
                            }
                        } catch (AWTError e) {
                            showCatchError(e);
                            if (inAnApplet) {
                                statusMsg(
                                        e.toString()
                                                + "  (probably due to security restrictions)");
                            }
                        } finally {
                            if (inAnApplet) {
                                setEnabled(true);
                            }
                        }
 
                        FileState = false;
                    } else {
                        writeFile(currFile.toString());
                    }
                } else if (buttonLabel.equals(MI_NEW)) {
                    newFile();
                }

            }

            taText.requestFocus();
        }// end of ActionPerformed
    }// end of ButtonListener
}


// **************************************
// * This provides a frame for the Applet
// **************************************
class DrawFrame extends Frame {
    
	static final long serialVersionUID = 1L;
	Draw teApplet;

    public DrawFrame(Draw t, String Title) {
        setTitle(Title);
        teApplet = t;

        teApplet.inAnApplet = false;
        // Call init() method as a browser would
        teApplet.init();
        add("Center", teApplet);
        teApplet.parent = (Frame) this;

        super.enableEvents(AWTEvent.WINDOW_EVENT_MASK | AWTEvent.KEY_EVENT_MASK);
        pack();
        setVisible(true);
    }

    protected void processEvent(AWTEvent evt) {
        // Forward all events to Applet class
        if (teApplet != null) {
            teApplet.callProcessEvent(evt);
        } else { 
            super.processEvent(evt);
        }
    }
}
