/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package grader.UI;

import grader.UI.file.ExportSIS;
import grader.UI.file.ExportServer;
import grader.UI.file.Import;
import grader.UI.file.Login;
import grader.UI.file.MidRosterSync;
import grader.UI.gradebook.AddCategory;
import grader.UI.gradebook.AddItem;
import grader.UI.gradebook.CategoryAndItemManager;
import grader.UI.gradebook.Gradebook;
import grader.UI.help.GraderAboutBox;
import grader.UI.student.NewStudent;
import grader.UI.student.StudentManager;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.GroupLayout;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JSeparator;
import javax.swing.LayoutStyle;
import javax.swing.Timer;

import org.jdesktop.application.Action;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.TaskMonitor;

/**
 *  The application's main frame.
 *
 * @author Kellen
 */
public class GraderView extends FrameView {

    public GraderView(SingleFrameApplication app) {
        super(app);

        initComponents();

        desktop = new JDesktopPane();
        desktop.setBackground(Color.GRAY);
        setComponent(desktop);

        // status bar initialization - message timeout, idle icon and busy animation, etc
//        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = 10;
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
//        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
//            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = null; //new Timer(busyAnimationRate, new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
//                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
//            }
//        });
        idleIcon = null; //resourceMap.getIcon("StatusBar.idleIcon");
//        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }


    // <editor-fold defaultstate="collapsed" desc="All menu action methods">

    /*
     * Menu Actions Methods
     */

    // File Menu
//    @Action
//    public void showNew() {
//        if (importWizard == null) {
//            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
//            importWizard = new Import(mainFrame, true);
//            importWizard.setLocationRelativeTo(mainFrame);
//        }
//        GraderApp.getApplication().show(importWizard);
//    }
//    @Action
//    public void showSave() {
//        if (importWizard == null) {
//            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
//            importWizard = new Import(mainFrame, true);
//            importWizard.setLocationRelativeTo(mainFrame);
//        }
//        GraderApp.getApplication().show(importWizard);
//    }
//    @Action
//    public void showSaveAs() {
//        if (importWizard == null) {
//            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
//            importWizard = new Import(mainFrame, true);
//            importWizard.setLocationRelativeTo(mainFrame);
//        }
//        GraderApp.getApplication().show(importWizard);
//    }
    @Action
    public void showLogin() {
        if (login == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            login = new Login(mainFrame, true);
            login.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(login);
    }
    @Action
    public void showMidTermSync() {
        if (midTermSync == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            midTermSync = new MidRosterSync(mainFrame, true);
            midTermSync.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(midTermSync);
    }
    @Action
    public void showImport() {
        if (importWizard == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            importWizard = new Import(mainFrame, true);
            importWizard.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(importWizard);
    }
    @Action
    public void showExportServer() {
        if (exportToServer == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            exportToServer = new ExportServer(mainFrame, true);
            exportToServer.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(exportToServer);
    }
    @Action
    public void showExportSIS() {
        if (exportToSIS == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            exportToSIS = new ExportSIS(mainFrame, true);
            exportToSIS.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(exportToSIS);
    }

    // Edit Menu

    // View Menu

    // Tools Menu

    // Gradebook Menu
    @Action
    public void showNewGradedItem() {
        if (addItem == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            addItem = new AddItem(mainFrame, true);
            addItem.setLocationRelativeTo(mainFrame);
            addItem.pack();
        }
        GraderApp.getApplication().show(addItem);
    }
    @Action
    public void showNewCategory() {
        if (addCategory == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            addCategory = new AddCategory(mainFrame, true);
            addCategory.setLocationRelativeTo(mainFrame);
            addCategory.pack();
        }
        GraderApp.getApplication().show(addCategory);
    }
    @Action
    public void showCatManager() {
        if (catAndItemManger == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            catAndItemManger = new CategoryAndItemManager(mainFrame, false);
            catAndItemManger.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(catAndItemManger);
    }
    // Students Menu
    @Action
    public void showNewStudent() {
        if (newStudent == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            newStudent = new NewStudent(mainFrame, false);
            newStudent.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(newStudent);
    }
    @Action
    public void showStudentManager() {
        if (studentManger == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            studentManger = new StudentManager(mainFrame, false);
            studentManger.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(studentManger);
    }
    // Window Menu
    @Action
    public void showGradebook() {
        if ((gradebook == null) || (gradebook.isClosed())) {
            gradebook = new Gradebook("CSC 308", true, true, true, true);
            gradebook.setBounds(50, 50, 200, 100);
            desktop.add(gradebook, new Integer(1));
            gradebook.pack();
            gradebook.setVisible(true);
            try {
                gradebook.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
        }

    }
//
//    @Action
//    public void showPieChart() {
//        if ((piechart == null) || (piechart.isClosed())) {
//            piechart = new Gradebook("Pie Chart", true, true, true, true);
//            piechart.setBounds(50, 50, 200, 100);
//            desktop.add(piechart, new Integer(1));
//            piechart.setVisible(true);
//            try {
//                piechart.setSelected(true);
//            } catch (java.beans.PropertyVetoException e) {}
//        }
//
//    }
//
//    @Action
//    public void showHistogram() {
//        if ((histogram == null) || (histogram.isClosed())) {
//            histogram = new Gradebook("Histogram", true, true, true, true);
//            histogram.setBounds(50, 50, 200, 100);
//            desktop.add(histogram, new Integer(1));
//            histogram.setVisible(true);
//            try {
//                histogram.setSelected(true);
//            } catch (java.beans.PropertyVetoException e) {}
//        }
//
//    }

    @Action
    public void showGradingRange() {
        if ((gradingScheme == null) || (gradingScheme.isClosed())) {
            gradingScheme = new GradingScheme();
            gradingScheme.setBounds(50, 50, 650, 500);
            desktop.add(gradingScheme, new Integer(1));
            gradingScheme.pack();
            gradingScheme.setSize(650, 500);
            gradingScheme.setVisible(true);
            try {
                gradingScheme.setSelected(true);
            } catch (java.beans.PropertyVetoException e) {}
        }

    }
    


    // Help Menu
    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = GraderApp.getApplication().getMainFrame();
            aboutBox = new GraderAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        GraderApp.getApplication().show(aboutBox);
    }
    // </editor-fold>


    /**
     * Sets up a menu item with the a name and assosiate an action to the item
     */
    private void setupMenuItem(JMenuItem item, String name, String actionName){
        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(grader.UI.GraderApp.class).getContext().getActionMap(GraderView.class, this);
        item.setAction(actionMap.get(actionName));
        item.setText(name);
        item.setName(name + "MenuItem");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     */
    private void initComponents() {
       
       initMenuItems();

        /*
         * setup the status panel
         */
        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        /*
         * Create the layout for the window
         */
        GroupLayout statusPanelLayout = new GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE)
                .addComponent(progressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        /*
         * Set all the components
         */
        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }

    private void initMenuItems(){
        menuBar = new JMenuBar();
        fileMenu = new JMenu();        
        newMenuItem = new JMenuItem();
        openMenuItem = new JMenuItem();
        saveMenuItem = new JMenuItem();
        saveAsMenuItem = new JMenuItem();
        jSeparator1 = new JSeparator();
        loginMenuItem = new JMenuItem();
        midTermSyncMenuItem = new JMenuItem();
        importMenuItem = new JMenuItem();
        exportMenu = new JMenu();
        exportServerMenuItem = new JMenuItem();
        exportSisMenuItem = new JMenuItem();
        jSeparator2 = new JSeparator();
        exitMenuItem = new JMenuItem();
        editMenu = new JMenu();
        undoMenuItem = new JMenuItem();
        redoMenuItem = new JMenuItem();
        revertMenuItem = new JMenuItem();
        viewMenu = new JMenu();
        toolbarsMenu = new JMenu();
        zoomMenu = new JMenu();
        jSeparator3 = new JSeparator();
        switchViewMenuItem = new JMenuItem();
        toolsMenu = new JMenu();
        findMenuItem = new JMenuItem();
        optionsMenuItem = new JMenuItem();
        gradebookMenu = new JMenu();
        newGradedItemMenuItem = new JMenuItem();
        newCategoryMenuItem = new JMenuItem();
        jSeparator4 = new JSeparator();
        catManagerMenuItem = new JMenuItem();
        studentMenu = new JMenu();
        newStudentMenuItem = new JMenuItem();
        studentManagerMenuItem = new JMenuItem();
        windowMenu = new JMenu();
        showGradebook = new JCheckBoxMenuItem();
        showPieChartMenuItem = new JMenuItem();
        showHistogramMenuItem = new JMenuItem();
        showGradingRangeMenuItem = new JMenuItem();
        helpMenu = new JMenu();
        contentsMenuItem = new JMenuItem();
        aboutMenuItem = new JMenuItem();
        statusPanel = new JPanel();
        statusPanelSeparator = new JSeparator();
        statusMessageLabel = new JLabel();
        statusAnimationLabel = new JLabel();
        progressBar = new JProgressBar();

         /*
         * Setup all the menus and menu items
         */
        menuBar.setName("menuBar");

//        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(grader.UI.GraderApp.class).getContext().getResourceMap(GraderView.class);
        fileMenu.setText("File");
        fileMenu.setName("fileMenu");

        setupMenuItem(newMenuItem, "New", "showNew");
        fileMenu.add(newMenuItem);

        setupMenuItem(openMenuItem, "Open", "showOpen");
        fileMenu.add(openMenuItem);

        setupMenuItem(saveMenuItem, "Save", "showSave");
        fileMenu.add(saveMenuItem);

        setupMenuItem(saveAsMenuItem, "SaveAs", "showSaveAs");
        fileMenu.add(saveAsMenuItem);

        jSeparator1.setName("jSeparator1");
        fileMenu.add(jSeparator1);

        setupMenuItem(loginMenuItem, "Login", "showLogin");
        fileMenu.add(loginMenuItem);

        setupMenuItem(midTermSyncMenuItem, "MidTermSync", "showMidTermSync");
        fileMenu.add(midTermSyncMenuItem);

        setupMenuItem(importMenuItem, "Import", "showImport");
        fileMenu.add(importMenuItem);

        exportMenu.setText("Export");
        exportMenu.setName("exportMenu");
        
        setupMenuItem(exportServerMenuItem, "Export to Server", "showExportServer");
        exportMenu.add(exportServerMenuItem);
        
        setupMenuItem(exportSisMenuItem, "Export to SIS", "showExportSIS");
        exportMenu.add(exportSisMenuItem);
        
        fileMenu.add(exportMenu);

        jSeparator2.setName("jSeparator2");
        fileMenu.add(jSeparator2);

//        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        setupMenuItem(exitMenuItem, "Exit", "quit");
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setText("Edit");
        editMenu.setName("editMenu");

        setupMenuItem(undoMenuItem, "Undo", "show");
        editMenu.add(undoMenuItem);

        setupMenuItem(redoMenuItem, "Redo", "show");
        editMenu.add(redoMenuItem);

        setupMenuItem(revertMenuItem, "Revert", "show");
        editMenu.add(revertMenuItem);

        menuBar.add(editMenu);

        viewMenu.setText("View");
        viewMenu.setName("viewMenu");

        setupMenuItem(toolbarsMenu, "Toolbars", "showToolbars");
        viewMenu.add(toolbarsMenu);

        setupMenuItem(zoomMenu, "Zoom", "showZoom");
        viewMenu.add(zoomMenu);

        jSeparator3.setName("jSeparator3");
        viewMenu.add(jSeparator3);

        setupMenuItem(switchViewMenuItem, "Switch View", "showSwitchView");
        viewMenu.add(switchViewMenuItem);

        menuBar.add(viewMenu);

        toolsMenu.setText("Tools");
        toolsMenu.setName("toolsMenu");

        setupMenuItem(findMenuItem, "Find", "showFind");
        toolsMenu.add(findMenuItem);

        setupMenuItem(optionsMenuItem, "Options", "showOptions");
        toolsMenu.add(optionsMenuItem);

        menuBar.add(toolsMenu);

        gradebookMenu.setText("Gradebook");
        gradebookMenu.setName("gradebookMenu");

        setupMenuItem(newGradedItemMenuItem, "New Graded Item", "showNewGradedItem");
        gradebookMenu.add(newGradedItemMenuItem);

        setupMenuItem(newCategoryMenuItem, "New Category", "showNewCategory");
        gradebookMenu.add(newCategoryMenuItem);

        jSeparator4.setName("jSeparator4");
        gradebookMenu.add(jSeparator4);

        setupMenuItem(catManagerMenuItem, "Category & Item Manager", "showCatManager");
        gradebookMenu.add(catManagerMenuItem);

        menuBar.add(gradebookMenu);

        studentMenu.setText("Student");
        studentMenu.setName("studentMenu");

        setupMenuItem(newStudentMenuItem, "New Student", "showNewStudent");
        studentMenu.add(newStudentMenuItem);

        setupMenuItem(studentManagerMenuItem, "Student Manager", "showStudentManager");
        studentMenu.add(studentManagerMenuItem);

        menuBar.add(studentMenu);

        windowMenu.setText("Window");
        windowMenu.setName("windowMenu");

        setupMenuItem(showGradebook, "Gradebook", "showGradebook");
        windowMenu.add(showGradebook);

        setupMenuItem(showPieChartMenuItem, "Pie Chart", "showPieChart");
        windowMenu.add(showPieChartMenuItem);

        setupMenuItem(showHistogramMenuItem, "Histogram", "showHistogram");
        windowMenu.add(showHistogramMenuItem);

        setupMenuItem(showGradingRangeMenuItem, "Grading Range", "showGradingRange");
        windowMenu.add(showGradingRangeMenuItem);

        menuBar.add(windowMenu);

        helpMenu.setText("Help");
        helpMenu.setName("helpMenu");

        setupMenuItem(contentsMenuItem, "Contents", "showContents");
        helpMenu.add(contentsMenuItem);

        setupMenuItem(aboutMenuItem, "About", "showAbout");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);
    }

    // <editor-fold defaultstate="collapsed" desc="All local variables">

    private JMenuBar menuBar;
    // file menu items
    private JMenu fileMenu;
    private JMenuItem newMenuItem;
    private JMenuItem openMenuItem;
    private JMenuItem saveMenuItem;
    private JMenuItem saveAsMenuItem;
    private JMenuItem loginMenuItem;
    private JMenuItem midTermSyncMenuItem;
    private JMenuItem importMenuItem;
    private JMenu exportMenu;
    private JMenuItem exportServerMenuItem;
    private JMenuItem exportSisMenuItem;
    private JMenuItem exitMenuItem;
    // edit menu items
    private JMenu editMenu;
    private JMenuItem undoMenuItem;
    private JMenuItem redoMenuItem;
    private JMenuItem revertMenuItem;
    // view menu items
    private JMenu viewMenu;
    private JMenu toolbarsMenu;
    private JMenu zoomMenu;
    private JMenuItem switchViewMenuItem;
    // tools menu items
    private JMenu toolsMenu;
    private JMenuItem findMenuItem;
    private JMenuItem optionsMenuItem;
    // gradebook menu items
    private JMenu gradebookMenu;
    private JMenuItem newCategoryMenuItem;
    private JMenuItem newGradedItemMenuItem; 
    private JMenuItem catManagerMenuItem;
    // student menu items
    private JMenu studentMenu;
    private JMenuItem newStudentMenuItem;
    private JMenuItem studentManagerMenuItem;
    // window menu items
    private JMenu windowMenu;
    private JMenuItem showGradingRangeMenuItem;
    private JMenuItem showPieChartMenuItem;
    private JMenuItem showHistogramMenuItem;   
    // help menu items
    private JMenu helpMenu;
    private JMenuItem contentsMenuItem;
    private JMenuItem aboutMenuItem;
    
    private JSeparator jSeparator1;
    private JSeparator jSeparator2;
    private JSeparator jSeparator3;
    private JSeparator jSeparator4;
    private JSeparator statusPanelSeparator;

    private JCheckBoxMenuItem showGradebook;
    
    
    private JProgressBar progressBar;
    private JLabel statusAnimationLabel;
    private JLabel statusMessageLabel;
    private JPanel statusPanel;    
    private JPanel mainPanel;
    
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDesktopPane desktop;

    private JDialog aboutBox;

    private Gradebook gradebook;
    private Gradebook piechart;
    private Gradebook histogram;
    private GradingScheme gradingScheme;

    private JDialog exportToServer;
    private JDialog exportToSIS;
    private JDialog importWizard;
    private JDialog midTermSync;
    private JDialog addCategory;
    private JDialog addItem;
    private JDialog login;
    private JDialog catAndItemManger;
    private JDialog newStudent;
    private JDialog studentManger;


    // </editor-fold>
}