/* Menu.java
 * 
 * This class is the menu at the top of the window.
 *
 * Author: Michael A. Piskuric (2537405) Summer 2005
 */

import Robot.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public class Menu extends JMenuBar implements ActionListener {
    	
    private TeachVAL    parent;                 // parent window
    private JMenu       projMenu;               // the menu
    private boolean     runAllowed = false;     // allowed to run a program?
    private boolean     compileAllowed = true;  // allowed to compile??
    
    // initilize the menu and add it to the parent window
    public Menu(TeachVAL tv) {
        parent = tv;
        add(file());
        add(edit());
        add(projMenu = project());
        add(comm());
        add(help());					
        parent.setJMenuBar(this);
    }
    
    // this caputres all actions on the menu and does 
    // the appropriate thing
    public void actionPerformed(ActionEvent e) {
        String temp = ((JMenuItem)e.getSource()).getText();
        
        if(temp == "Exit")                  parent.exit();
        else if(temp == "Run")              parent.getCompiler().execute();
        else if(temp == "Compile")          parent.getCompiler().compile();
        else if(temp == "Cut       Ctrl+X") parent.getEditPanel().cut();
        else if(temp == "Paste   Ctrl+V")   parent.getEditPanel().paste();
        else if(temp == "Copy    Ctrl+C")   parent.getEditPanel().copy();
        else if(temp == "Open Port")        new PortDialog(parent);
        else if(temp == "About")            new AboutDialog();
        else if(temp == "Open")             openFile();
        else if(temp == "Save As")             saveFile();
        else if(temp == "Help")             new TVHelp();
        else if(temp == "Print")            parent.getEditPanel().print();        
        else if(temp == "Compile then Run") {
            parent.getCompiler().compile();
            if(runAllowed) parent.getCompiler().execute();
        }        
        else if(temp == "Empty File") {
            parent.getEditPanel().setText("");
            resetAll();
        }
        else if(temp == "From Template") {
            parent.getEditPanel().setText(getTemplate());
            resetAll();
        }        
        else parent.getStatusBar().setText(temp);
    }
    
    // opens a file chooser and allows the user to choose a 
    // file to open and then it displays it in the edit window
    private void openFile() {
        String text = "";
        JFileChooser fileChooser = new JFileChooser(new File(System.getProperty("user.home")));
        fileChooser.addChoosableFileFilter(new JavaFilter());
        
        if(fileChooser.showOpenDialog(parent) == fileChooser.APPROVE_OPTION) {
            parent.getCompiler().clear();
            resetAll();
            try {
                BufferedReader in = new BufferedReader(new FileReader(fileChooser.getSelectedFile().getPath()));
                while(true) {
                    String temp = in.readLine();
                    if(temp == null) break;
                    else if(temp.trim().compareTo("//COMPILER GENERATED CODE; DO NOT MODIFY")== 0) {
                        temp = in.readLine();
                        while(temp.trim().compareTo("//COMPILER GENERATED CODE; DO NOT MODIFY")!= 0) {
                            parse(temp.trim());
                            temp = in.readLine();
                        }
                    }
                    else text += temp + "\n";
                }            
            }
            catch (Exception e) {new TVException(e.getMessage());};
            parent.getEditPanel().setText(text);            
            parent.getStatusBar().setText("File opened successfully.");
        }
    }   // end open file
    
    // this methos parses out the location and makes the 
    // point show up in the point panel
    private void parse(String loc) {
        StringTokenizer st = new StringTokenizer(loc,"(), ");
        st.nextToken();
        String name = st.nextToken();
        st.nextToken();
        st.nextToken();
        st.nextToken();
        double x = Double.parseDouble(st.nextToken());
        double y = Double.parseDouble(st.nextToken());
        double z = Double.parseDouble(st.nextToken());
        double p = Double.parseDouble(st.nextToken());
        double r = Double.parseDouble(st.nextToken());
        parent.getPointPanel().addNewPoint(new Location(x,y,z,p,r,name));
    }
    
    // opens a save dialog and allows the user to save the file
    // they are currently working on
    private void saveFile() {
        JFileChooser fileChooser = new JFileChooser(new File(System.getProperty("user.home"))); 
        fileChooser.addChoosableFileFilter(new JavaFilter());
               
        if(fileChooser.showSaveDialog(parent) == fileChooser.APPROVE_OPTION) {
            try {
                File outFile = fileChooser.getSelectedFile();
                if(!outFile.exists() | (outFile.exists() && parent.confirm("Do you want to overwrite the existing file?"))) {
                    FileWriter out = new FileWriter(outFile);
                    String theText = parent.getEditPanel().getText();
              
                    out.write(parent.getCompiler().insertPoints(theText));
                    out.close();
                    parent.getStatusBar().setText("File saved successfully.");
                }
            }
            catch (Exception e) {new TVException(e.getMessage());};
        }
    }   // end saveFile
    
    // toggles the run option in the Project submenu
    public void setRun(boolean b){
        runAllowed = b;
        projMenu.getItem(1).setEnabled(runAllowed);
    }
    
    // toggles the compile option in the Project submenu
    public void setCompile(boolean b){
        compileAllowed = b;
        projMenu.getItem(0).setEnabled(compileAllowed);
    }    
    	
    // creates the file submenu
    private JMenu file () {
        JMenu theMenu = new JMenu("File");
        
        JMenu newMenu = new JMenu("New");
            JMenuItem newProg = new JMenuItem("Empty File");
            newProg.addActionListener(this);
            newMenu.add(newProg);
            
            JMenuItem newTemplate = new JMenuItem("From Template");
            newTemplate.addActionListener(this);
            newMenu.add(newTemplate);            
            
        theMenu.add(newMenu);    
        JMenuItem open = new JMenuItem("Open");
        open.addActionListener(this);
        theMenu.add(open);
        JMenuItem save = new JMenuItem("Save As");
        save.addActionListener(this);
        theMenu.add(save);
        theMenu.addSeparator();
        JMenuItem print = new JMenuItem("Print");
        print.addActionListener(this);
        theMenu.add(print);
        theMenu.addSeparator();
        JMenuItem exit = new JMenuItem("Exit");
        exit.addActionListener(this);
        theMenu.add(exit);
        return theMenu;	
    }
   
    // creates the edit submenu
    private JMenu edit () {
        JMenu theMenu = new JMenu("Edit");    		
        JMenuItem cut = new JMenuItem("Cut       Ctrl+X");
        cut.addActionListener(this);
        theMenu.add(cut);
        JMenuItem copy = new JMenuItem("Copy    Ctrl+C");
        copy.addActionListener(this);
        theMenu.add(copy);
        JMenuItem paste = new JMenuItem("Paste   Ctrl+V");
        paste.addActionListener(this);
        theMenu.add(paste);       		
        return theMenu;
    }
    
    // creates the help submenu
    private JMenu help () {
        JMenu theMenu = new JMenu("Help");    		
        JMenuItem help = new JMenuItem("Help");
        help.addActionListener(this);
        theMenu.add(help);
        theMenu.addSeparator();
        JMenuItem about = new JMenuItem("About");
        about.addActionListener(this);
        theMenu.add(about);    		
        return theMenu;  		
    }
   
    // creates the ports submenu
    private JMenu comm() {
        JMenu theMenu = new JMenu("Ports");    		
        JMenuItem open = new JMenuItem("Open Port");
        open.addActionListener(this);
        theMenu.add(open);
        return theMenu;
    }
    
    // creates the project submenu
    private JMenu project() {
        JMenu theMenu = new JMenu("Project"); 
        JMenuItem compile = new JMenuItem("Compile");
        compile.addActionListener(this);
        compile.setEnabled(compileAllowed);
        theMenu.add(compile);
        JMenuItem run = new JMenuItem("Run");
        run.addActionListener(this);
        run.setEnabled(runAllowed);
        theMenu.add(run);
        theMenu.addSeparator();
        JMenuItem compileRun = new JMenuItem("Compile then Run");
        compileRun.addActionListener(this);
        compileRun.setEnabled(true);
        theMenu.add(compileRun);        
        return theMenu;
    }
    
    // restets the entire program like from startup
    private void resetAll(){
        setRun(false); 
        setCompile(true);
        parent.getCompiler().clear();
        parent.getPointPanel().clearPoints(); 
    }
    
    // returns the "template" for starting out
    private String getTemplate() {
        String text = "import Robot.*;\n\n";
        text += "public class ClassNameHere {\n\n";
        text += "\tprivate Microbot    robot = new Microbot(\"COM1\");\n\n";   
        text += "\tpublic ClassNameHere() {\n\n\n";
        text += "\t\trobot.closePort();\n\t}\n\n";
        text += "\tpublic static void main(String args[]) {new ClassNameHere();};\n\n";
        text += "}";        
        return text;
    }
    
    // internal class is a file filter for the file chooser
    public class JavaFilter extends javax.swing.filechooser.FileFilter {
        
        public boolean accept(File file) {
            String ext = "";
            
            if (file.getPath().lastIndexOf('.') > 0)
                    ext = file.getPath().substring(file.getPath().lastIndexOf('.')+1).toLowerCase();
            
            if (ext != "")
                    return (ext.equals("java") | ext.equals("JAVA")) ;
            else
                return file.isDirectory();
        }    
        
        public String getDescription () {
            return "Java Files (*.java)";
        }
    }
}   // end Menu