/* ---------------------------------------------------------------
 File:                           Tutorial.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 Tutorial extends Applet {
    
	// Data members
	static final long serialVersionUID = 1L;
	static TutorialFrame appFrame = null;
    Toolkit   toolKit = Toolkit.getDefaultToolkit();
    public TextArea  taText;

    Choice  cFontNames, cFontSizes;
    public Frame parent;
    Label statusBar;
    static String MI_NEW = "New",
            MI_OPEN = "Open...",
            MI_CLOSE = "Close",

            COMPMA = "About F.S.M Analysis",
            FIL = "File Menu",
            APPL = "Applications Menu",
            RN = "Run Menu",
            DF = "Data File Windows",
            RS = "Results File Window",
            INTROV = "Introduction & Overview",
            IOF = "I/O Format and Data Structures",
            ALLF = "All The Functions",
            TPF = "Top Level Functions",
            LLF = "Lower Level Functions",
            ANF = "Additional New Functions",
            RSV = "Reserved Words & Error Msgs",
            CONC = "Conclusions",
		    
            DEF_FNAME = "TimesRoman",
            DEF_FSIZE = "14",
            NEW_FILE = "untitled.txt";

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

    // "init" invoked automatically when run as an
    // applet or if directly called by another class
    public void init() {
        setBackground(Color.lightGray);

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

        // Font Tool Bar
        fontPanel = new Panel();
        fontPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
       
        // Push Button Tool Bar
        buttonPanel = new Panel();
        buttonPanel.setFont(new Font("TimesRoman", Font.BOLD, 14));
        buttonPanel.setLayout(new GridLayout(1, 40));

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

        // Text Editing Area (20 rows x 80 cols)
        taText = new TextArea(35, 58);
        taText.setBackground(Color.white);

        // 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 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);
        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 MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            statusMsg("");

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

                if (menuLabel.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 (menuLabel.equals(MI_NEW)) {
                    newFile();
                } else if (menuLabel.equals(MI_CLOSE)) {
                    parent.setVisible(false);
                    parent.dispose();
                } else if (evt.getSource() instanceof MenuItem) {
                    if (evt.getActionCommand().equals(COMPMA)) {
                        readFile("../manual/intro.tex");
                    } else if (evt.getActionCommand().equals(INTROV)) {
                        readFile("../manual/intro.tex");
                    } else if (evt.getActionCommand().equals(IOF)) {
                        readFile("../manual/io.tex");
                    } else if (evt.getActionCommand().equals(ALLF)) {
                        readFile("../manual/all_func.tex");
                    } else if (evt.getActionCommand().equals(TPF)) {
                        readFile("../manual/tl_func.tex");
                    } else if (evt.getActionCommand().equals(LLF)) {
                        readFile("../manual/ll_func.tex");
                    } else if (evt.getActionCommand().equals(ANF)) {
                        readFile("../manual/add_func.tex");
                    } else if (evt.getActionCommand().equals(RSV)) {
                        readFile("../manual/rsv.tex");
                    } else if (evt.getActionCommand().equals(CONC)) {
                        readFile("../manual/conc.tex");
                    }

                }// if it's a menu item
     
            }// end of outer if

            taText.requestFocus();
        }// end of actionPerformed
    }// end of MyActionListener

}


// **************************************
// * This provides a frame for the Applet
// **************************************
class TutorialFrame extends Frame {
    
	Tutorial teApplet;
	static final long serialVersionUID = 1L;
	
    public TutorialFrame(Tutorial t, String Title,
            String openWithFile) {
        setTitle(Title);
        teApplet = t;

        // Build Book Sections Menu
        Menu Ap1 = new Menu("Book-Sections");

        Ap1.add(new MenuItem(Tutorial.COMPMA));
        Ap1.add(new MenuItem(Tutorial.INTROV));
        Ap1.add(new MenuItem(Tutorial.IOF)); 

        Menu hold3 = new Menu("Menus");

        hold3.add(new MenuItem(Tutorial.FIL));
        hold3.add(new MenuItem(Tutorial.APPL));
        hold3.add(new MenuItem(Tutorial.RN));
        Ap1.add(hold3);

        Menu hold4 = new Menu("Windows");

        hold4.add(new MenuItem(Tutorial.DF));
        hold4.add(new MenuItem(Tutorial.RS));
        Ap1.add(hold4);

        Menu hold2 = new Menu("Underlying Functions");

        hold2.add(new MenuItem(Tutorial.ALLF));
        hold2.add(new MenuItem(Tutorial.TPF));
        hold2.add(new MenuItem(Tutorial.LLF));
        hold2.add(new MenuItem(Tutorial.ANF));
        Ap1.add(hold2);

        Ap1.add(new MenuItem(Tutorial.RSV));
        Ap1.add(new MenuItem(Tutorial.CONC));
        Ap1.addActionListener(teApplet.new MyActionListener());  

        // Add Menu Bar and Menu to Frame
        MenuBar mb = new MenuBar();
        mb.add(Ap1);
        setMenuBar(mb);

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

        // Open a file if requested
        if (openWithFile != null) {
            teApplet.readFile(openWithFile);
        } 

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

    }
}
