/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/03/17, 18:02
!  AUTHOR(S): KOGA, Junichiro
!  File : ChaseJMenuItems.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */

package ciss.phase_viewer.mainpanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

import org.apache.log4j.Logger;

import ciss.phase_viewer.acviewer.CoordsViewerInterface;
import ciss.phase_viewer.common.ChaseFileChooser;
import ciss.phase_viewer.common.ConstParameters;
import ciss.phase_viewer.common.ExternalProgramExecuter;
import ciss.phase_viewer.common.MyJMenu;
import ciss.phase_viewer.common.MyJMenuItem;
import ciss.phase_viewer.common.MyThread;
import ciss.phase_viewer.common.Utils;
import ciss.phase_viewer.jdom.MyElement;
import ciss.phase_viewer.main.Main;
import ciss.phase_viewer.pkg.ActivationPanel;
import ciss.phase_viewer.process.ProcessViewer;
import ciss.phase_viewer.projectbrowser.Restorer;
import ciss.phase_viewer.projectbrowser.projectdirbrowser.ProjectDirBrowser;
import ciss.phase_viewer.settings.ExternalProgramSelector;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;
import ciss.phase_viewer.ssh.hosts.HostConfigurator;
import ciss.phase_viewer.ssh.hosts.HostInfo;
import ciss.phase_viewer.ssh.hosts.HostList;
import ciss.phase_viewer.ssh.sftp.SftpClient;
import ciss.phase_viewer.ssh.terminal.Terminal;
import ciss.phase_viewer.textviewer.HelpViewer;

/**
 * 一番上位のメニューの配列を作成するクラス.
 * 
 * @author
 */
public class ChaseJMenuItems {
    private Logger logger = Logger.getLogger(ChaseJMenuItems.class.getName());
    private Vector menuItems = new Vector();

    private GlobalProperties propChase = PropertiesManager
            .getGlobalProperties(PropertiesManager.PROPERTIES_PVIEWER);

    private final String FS = System.getProperty("file.separator");
    private final String PS = System.getProperty("path.separator");
    private final String CR = System.getProperty("line.separator");

    /** Creates a new instance of ChaseJMenuItems */
    public ChaseJMenuItems() {
        createMenu();
    }

    public JMenuItem[] getMenuItems() {
        JMenuItem[] items = new JMenuItem[menuItems.size()];
        for (int i = 0; i < items.length; i++) {
            items[i] = (JMenuItem) menuItems.get(i);
        }
        return items;
    }

    private ProjectDirBrowser dirBrowser;

    private void fileMenu() {
        ProjectDirBrowser dirBrowser = ChaseGUI.getProjectDirBrowser();
        DirBrowserMenu dirMenu = new DirBrowserMenu("Project", KeyEvent.VK_P,
                dirBrowser);
        menuItems.add(dirMenu);
    }

    private void createMenu() {
        LookandFeel l_and_f = new LookandFeel();
        fileMenu();

        MyJMenu modulemenu = new MyJMenu("Module", KeyEvent.VK_M);
        MyJMenu networkmenu = modulemenu;
        MyJMenuItem sshterminal = new MyJMenuItem("ssh terminal", KeyEvent.VK_T);
        networkmenu.add(sshterminal);
        sshterminal.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Terminal term = new Terminal();
                term.setVisible(true);
            }
        });

        MyJMenuItem sftpclient = new MyJMenuItem("sftp client", KeyEvent.VK_F);
        networkmenu.add(sftpclient);
        sftpclient.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SftpClient sftp = new SftpClient();
            }
        });

        MyJMenuItem networkconfig = new MyJMenuItem("configure host info",
                KeyEvent.VK_C);
        networkmenu.add(networkconfig);
        networkconfig.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                HostConfigurator configurator = new HostConfigurator();
            }
        });
        modulemenu.addSeparator();
        menuItems.add(modulemenu);

        MyJMenu chasemenu = modulemenu;
        MyJMenuItem macv = new MyJMenuItem("atomic configuration viewer",
                KeyEvent.VK_A);
        macv.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootACViewer();
            }
        });
        chasemenu.add(macv);

        MyJMenuItem mgraph = new MyJMenuItem("graph tool", KeyEvent.VK_G);
        mgraph.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootGraphTool();
            }
        });
        chasemenu.add(mgraph);

        MyJMenuItem mimageView = new MyJMenuItem("image viewer", KeyEvent.VK_I);
        mimageView.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootImageLoader();
            }
        });
        chasemenu.add(mimageView);
        MyJMenuItem mexeviewer = new MyJMenuItem("BioStationViewer",
                KeyEvent.VK_B);
        chasemenu.add(mexeviewer);
        mexeviewer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootBSV();
            }
        });

        MyJMenu toolmenu = new MyJMenu("External tools", KeyEvent.VK_E);
        MyJMenuItem mexeeditor = new MyJMenuItem("Editor", KeyEvent.VK_D);
        mexeeditor.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootEditor();

            }
        });
        toolmenu.add(mexeeditor);
        toolmenu.addSeparator();

        MyJMenuItem mshell = new MyJMenuItem("shell", KeyEvent.VK_S);
        toolmenu.add(mshell);

        mshell.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootProcessFrame();
            }
        });

        MyJMenu processmenu = new MyJMenu("Process", KeyEvent.VK_R);
        MyJMenuItem mprocessViewer = new MyJMenuItem("Process Viewer",
                KeyEvent.VK_V);

        mprocessViewer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootProcessViewer();
            }
        });
        processmenu.add(mprocessViewer);
        ProcessMenu process = new ProcessMenu("Process", KeyEvent.VK_R);

        menuItems.add(process);

        MyJMenu prefs = new MyJMenu("Preferences", KeyEvent.VK_F);
        MyJMenuItem msetappl = new MyJMenuItem("program paths", KeyEvent.VK_P);
        msetappl.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ExternalProgramSelector foo = new ExternalProgramSelector();
            }
        });
        prefs.add(msetappl);

        WindowMenu window = new WindowMenu("Window(s)", KeyEvent.VK_W);
        menuItems.add(window);

        // 'look and feel' menu
        prefs.add(l_and_f);
        menuItems.add(prefs);

        MyJMenuItem restoreDefault = new MyJMenuItem(
                "restore default settings", KeyEvent.VK_R);
        restoreDefault.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                logger.info("restoring default settings...");

                String chaseini = System.getProperty("user.home")
                        + System.getProperty("file.separator")
                        + ".phase-viewer";
                if (new File(chaseini).exists()) {
                    try {
                        logger.info("your original .phase-viewer direrectory will be backed up to : "
                                + chaseini + "_bak");
                        new File(chaseini + "_bak").mkdir();
                        Utils.copyDir(new File(chaseini), new File(chaseini
                                + "_bak"));
                    } catch (Exception exc) {
                        exc.printStackTrace();
                    }
                }

                Chase.generateDefaultDotChaseDir(true);
            }
        });
        prefs.addSeparator();
        prefs.add(restoreDefault);

        menuItems.add(null);

        MyJMenu helpmenu = new MyJMenu("Help", KeyEvent.VK_H);

        MyJMenuItem mversion = new MyJMenuItem("Version", KeyEvent.VK_V);
        mversion.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootVersionDialog();
            }
        });
        helpmenu.add(mversion);

        MyJMenuItem mmanual = new MyJMenuItem("Online manual", KeyEvent.VK_M);
        mmanual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
        mmanual.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // org.jdom.Document doc = Main.getDefaultPropertiesDocument();
                // String helpdir =
                // doc.getRootElement().getChild("help").getChildTextTrim("htmlhelpdir");
                // String helpPath =
                // System.getProperty("pviewer.home")+FS+helpdir+FS+"index.html";
                HelpViewer browser = new HelpViewer();
            }
        });
        helpmenu.add(mmanual);

        MyJMenuItem mrestore = new MyJMenuItem("restore broken projects",
                KeyEvent.VK_R);

        mrestore.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                ChaseFileChooser cfc = new ChaseFileChooser();
                cfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if (cfc.showOpenDialog(Desk.getDesktop()) != JFileChooser.APPROVE_OPTION) {
                    logger.info("operation canceled.");
                    return;
                }
                File tmpFile = null;
                try {
                    tmpFile = File.createTempFile("tmp", "xml");
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("Failed to create a temp file; RESTORE FAILED!!");
                    return;
                }
                if (!Restorer.restore(cfc.getSelectedFile(), tmpFile)) {
                    logger.error("RESTORE FAILED!!");
                    return;
                }
                HostInfo info = HostList.getHostList().getHostInfo("localhost");
                info.setProperty("basedir", cfc.getSelectedFile()
                        .getAbsolutePath());
                HostList.getHostList().save();

                String myprojFile = System.getProperty("user.home")
                        + System.getProperty("file.separator")
                        + ".phase-viewer"
                        + System.getProperty("file.separator")
                        + "my_projects.xml";
                try {
                    ExternalProgramExecuter.copyBinary(
                            tmpFile.getAbsolutePath(), myprojFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("failed to recreate file : " + myprojFile);
                    logger.error("RESTORE FAILED!!");
                    return;
                }

                Main.getRootFrame().dispose();
                System.exit(0);
            }
        });

        helpmenu.addSeparator();
        helpmenu.add(mrestore);
        menuItems.add(helpmenu);
    }

    private void bootProcessViewer() {
        if (!ConstParameters.osName.toLowerCase().trim().startsWith("windows")) {
            ProcessViewer psv = new ProcessViewer();
            psv.start();
            psv.setVisible(true);
        } else {
            String taskmgr = propChase.getProperty("taskmgr");
            MyThread th = new MyThread(taskmgr);
        }
    }

    private void bootActivationPanel() {
        ActivationPanel ap = new ActivationPanel();
        ap.display();
    }

    private void bootVersionDialog() {
        org.jdom.Document doc = Main.getDefaultPropertiesDocument();
        org.jdom.Element elem = doc.getRootElement().getChild("version_dialog");

        String title = MyElement.decode(elem.getChildTextTrim("title").trim());
        String message = elem.getChildTextTrim("message");
        java.net.URL advancelogo = getClass().getResource(
                MyElement.decode(elem.getChildTextTrim("imagefilepath")));
        ImageIcon icon = null;
        if (advancelogo != null) {
            icon = new ImageIcon(advancelogo);
        }

        JOptionPane.showInternalMessageDialog(Desk.getDesktop(), message,
                title, JOptionPane.PLAIN_MESSAGE, icon);
    }

    private void bootEditor() {
        String editorPath = propChase.getProperty("editor");
        MyThread th = new MyThread(Utils.getPathDQ(propChase
                .getProperty("editor")));
    }

    private void bootBSV() {
        String BSVbooter = Utils.getPathDQ(ConstParameters.getJavaPath())
                + " -jar ";
        BSVbooter += Utils.getPathDQ(System.getProperty("pviewer.home") + FS
                + propChase.getProperty("BioStationViewer"));
        MyThread th = new MyThread(BSVbooter);
    }

    private void bootACViewer() {
        CoordsViewerInterface panel = new ciss.phase_viewer.acviewer.MainPanel();
        try {
            panel.display3D();
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }

    private void bootGraphTool() {
        ciss.phase_viewer.graph.dataset.DataSetManipulator manip = new ciss.phase_viewer.graph.dataset.DataSetManipulator();
    }

    private void bootImageLoader() {
        ciss.phase_viewer.imageviewer.ImageLoader imageLoader = new ciss.phase_viewer.imageviewer.ImageLoader(
                System.getProperty("user.home"));
        imageLoader.display();
    }

    private void bootProcessFrame() {
        ciss.phase_viewer.scripting.BshConsole console = new ciss.phase_viewer.scripting.BshConsole();
    }
}
