/* ---------------------------------------------------------------
 File:                           MainMenu.java
 Package:                        FLAP
 Author:                         Dr. Ratnesh Kumar and Greg Stamp
 V2.0 10/28/2006
 Initial Developers: Yana Ong, Bharath Oruganti and Magda & Octavian Procopiuc
 ---------------------------------------------------------------*/
 
/*
 * Dr. Ratnesh Kumar, Greg Stamp.
 * Department of Electrical and Computer Engineering
 * Iowa State University
 * October, 2006.
 *
 * Copyright (c) 2006
 * All rights reserved.
 */

package flap;


import java.awt.*;
import java.util.*;
import java.io.*;


/**
 * The initial menu which enables the user to open
 * as many Environment windows as he/she wants
 * with the desired machine type. Basically,
 * it contains one button for each machine type
 * and an exit button.
 */
public class MainMenu extends Frame {

	static final long serialVersionUID = 1L;
    Vector	windows = new Vector(1, 1);
    String	paramsFileName = ".flaprc";
    boolean	isApplet = false;
    Environment   target;

    public final static String STR_FSA = "FSM Designer";
    public final static String STR_QUIT = "QUIT";

    public final static String osName = System.getProperty("os.name");
    public final static String fileSeparator = System.getProperty(
            "file.separator");
    public static String workingDirectory = System.getProperty("user.dir");

    static {
        if (workingDirectory == null) {
            workingDirectory = "";
        } else if (!workingDirectory.endsWith(fileSeparator)) {
            workingDirectory += fileSeparator;
        }
    }
  
    public MainMenu(String args[], boolean isApplet) {
        super("FSM Designer");
        this.isApplet = isApplet;
        setLayout(new GridLayout(2, 1));
        Component c;
        Color color = Params._mm_backcolor;

        add(c = new Button(STR_FSA));
        c.setBackground(color);
        add(c = new Button(STR_QUIT));
        c.setBackground(color);
        if (args != null) {
            parseArgs(args);
        }
    }

    public boolean handleEvent(Event e) {
        if (e.id == Event.WINDOW_DESTROY) {
            quit(null);
        }
        return super.handleEvent(e);
    }

    public boolean action(Event e, Object arg) {
        Environment f;
        DialogThread actionThread;

        if (e.target instanceof Button) {
            if (STR_QUIT.equals(arg)) {
                target = null;
                actionThread = new DialogThread(this, 5);
                actionThread.start();       
            } else {
                if (!STR_FSA.equals(arg))
                    return false;
                
                f = createEnvironment(Environment.NO_FILE_NAME);
                f.setVisible(true);
            }
        } else if (e.target instanceof Environment) {
            if (Environment.CLOSE_STR.equals(arg)) {
                f = (Environment) e.target;
                windows.removeElement(f);
                f.setVisible(false);
            } else if (Environment.QUIT_STR.equals(arg)) {
                target = (Environment) e.target;
                actionThread = new DialogThread(this, 5);
                actionThread.start();  
            }
        }
        return super.action(e, arg);
    }

    public Dimension getPreferredSize() {
        return new Dimension(Params._mm_width, Params._mm_height);
    }

    /**
     * Checks if the user wants to save all the unsaved machines and
     * exits if the user didn't cancel the operation.
     */
    public boolean quit(Object first) {
        Environment f;

        if (first != null) {
            f = (Environment) first;
            f.setVisible(true);
            if (!f.testSavedAndProceed()) {
                return false;
            }
            windows.removeElement(f);
            f.setVisible(false);
        }
        int i = 0;

        while (i < windows.size()) {
            f = (Environment) windows.elementAt(i);
            f.setVisible(true);
            if (!f.testSavedAndProceed()) {
                return false;
            }
            windows.removeElement(f);
            f.setVisible(false);
        }
        setVisible(false); 
        dispose(); 
        return true;
    }	// end of method quit.
   
    /**
     * Parses the command line arguments.
     */
    void parseArgs(String args[]) {
        int		i = 0;
        String	arg;
        String	fileName = Environment.NO_FILE_NAME;

        while (i < args.length) {
            if (args[i].startsWith("-")) {
                arg = args[i++];
                if (i == 1) {
                    if (arg.equalsIgnoreCase("-p")) {
                        if (i < args.length) {
                            if (!args[i].startsWith("-")) {
                                paramsFileName = args[i++];
                            }
                        }
                    }
                    readParams();
                }
                if (i < args.length) {
                    if (!args[i].startsWith("-")) {
                        fileName = args[i++];
                    }
                }
                if (arg.equalsIgnoreCase("-fa")) {
                    createEnvironment(fileName);
                }
            }
        }
    }	// end of method parseArgs.

    /**
     * Reads the parameters from the parameters file.
     */
    protected void readParams() {
        FileInputStream	fis;
        Properties		params = new Properties();

        try {
            fis = new FileInputStream(paramsFileName);
            params.load(fis);
            fis.close();
        } catch (Exception e) {
            System.err.println("jflap: unable to open file " + paramsFileName);
            return;
        }
        Params.load(params);
    }

    /**
     * Creates a new environment and adds it to the list of windows
     * currently opened.
     */
    protected Environment createEnvironment(String aFileName) {
        Environment	f;

        setCursor(Frame.WAIT_CURSOR);
        f = new Environment(aFileName, (Container) this, isApplet);
        f.setSize(Params._e_width + 30, Params._e_height + 30);
        windows.addElement(f);
        f.setLocation(f.getX() + 20, f.getY() + 20);
        setCursor(Frame.DEFAULT_CURSOR);
        return f;
    }

    /**
     * Shows all the Environment windows.
     */
    public void showWindows() {
        Environment f;

        for (Enumeration e = windows.elements(); e.hasMoreElements();) {
            f = (Environment) e.nextElement();
            f.setVisible(true);
        }
    }

    void threadAction(int id) {
        quit(target);
    }

    /**
     * Helper file available for outside class; used to open a 
     * state machine file in graphic.
     */
    public void OpenFileAsGraphic(String aFileName) {
        Environment ev = createEnvironment(aFileName);

        ev.setVisible(true);
    }

}  // end of class MainMenu
