/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/03/17, 17:29
!  AUTHOR(S): KOGA, Junichiro
!  File : ExternalProgramSelector.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.settings;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;

import ciss.phase_viewer.mainpanel.InternalFrameChase;

/**
 * 外部プログラム選択用JPanel; 今のところ決め打ちだけどいずれもう少しマシにしよう.
 * 
 * @author
 */
public class ExternalProgramSelector extends InternalFrameChase {
    private Logger logger = Logger.getLogger(ExternalProgramSelector.class
            .getName());

    /** Creates a new instance of ExternalProgramSelector */
    public ExternalProgramSelector() {
        super("edit external program path", true, true, true, true,
                new Dimension(300, 180));
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(createPanelExternal(), BorderLayout.NORTH);
        getContentPane().add(buttons(), BorderLayout.SOUTH);
    }

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

    private JPanel createPanelExternal() {
        JPanel pext = new JPanel();
        pext.setLayout(new BoxLayout(pext, BoxLayout.Y_AXIS));
        // pext.setLayout(new FlowLayout());

        String editor = gp.getProperty("editor");
        String gs = gp.getProperty("gs");

        String os = System.getProperty("os.name").toLowerCase();
        if (editor == null || editor.trim().length() == 0) {
            if (os.startsWith("windows")) {
                editor = "NOTEPAD";
            } else {
                editor = "emacs";
            }
        }
        if (gs == null || gs.trim().length() == 0) {
            gs = getGSPath(os);
        }

        pext.add(new PathSelector(editor, "external editor",
                new PathSelectorAction() {
                    void doIt(String text) {
                        if (text != null && text.trim().length() != 0) {
                            gp.setProperty("editor", text);
                            gp.storeProperty();
                        }
                    }
                }, false));

        pext.add(new PathSelector(gs, "ghostscript", new PathSelectorAction() {
            void doIt(String text) {
                if (text != null && text.trim().length() != 0) {
                    gp.setProperty("gs", text);
                    gp.storeProperty();
                }
            }
        }, false));

        return pext;
    }

    private JPanel buttons() {
        JPanel pbtn = new JPanel();
        pbtn.setLayout(new BoxLayout(pbtn, BoxLayout.X_AXIS));

        JButton ok = new JButton("ok");
        JButton cancel = new JButton("cancel");
        pbtn.add(ok);
        pbtn.add(cancel);

        ok.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                for (int i = 0; i < pathSelectors.size(); i++) {
                    PathSelector selector = (PathSelector) pathSelectors.get(i);
                    selector.doAction();
                }
                dispose();
            }
        });
        cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                dispose();
            }
        });
        JPanel p = new JPanel();
        p.add(pbtn);
        return p;
    }

    private String getGSPath(String os) {
        if (!os.startsWith("windows")) {
            return "gs";
        }
        File[] root = File.listRoots();
        for (int i = 0; i < root.length; i++) {
            File[] foo = root[i].listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.equalsIgnoreCase("program files");
                }
            });
            if (foo == null || foo.length == 0) {
                continue;
            }
            File[] gsdir = foo[0].listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.equalsIgnoreCase("gs");
                }
            });
            if (gsdir == null || gsdir.length == 0) {
                continue;
            }
            File[] gssubdir = gsdir[0].listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.startsWith("gs");
                }
            });
            if (gssubdir == null || gsdir.length == 0) {
                continue;
            }
            return gssubdir[gssubdir.length - 1]
                    + System.getProperty("file.separator") + "bin"
                    + System.getProperty("file.separator") + "gswin32c.exe";
        }
        return "";
    }

    private Vector pathSelectors = new Vector();

    class PathSelector extends JPanel {
        private JTextField textField = new JTextField(30);
        private JButton jButton = new JButton("choose...");
        private PathSelectorAction action;
        private boolean dir = true;
        private String title;
        private String initPath;
        private JPanel panel;

        PathSelector(String initPath, String title, PathSelectorAction action,
                boolean dir) {
            this.dir = dir;
            this.initPath = initPath;
            this.title = title;
            this.action = action;
            this.panel = this;
            init();
        }

        PathSelector(String initPath, String title, PathSelectorAction action) {
            this.action = action;
            this.initPath = initPath;
            this.title = title;
            this.panel = this;
            init();
        }

        private void init() {
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
            setBorder(new TitledBorder(title));
            textField.setText(initPath);
            add(textField);
            add(jButton);
            jButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setDialogType(JFileChooser.OPEN_DIALOG);
                    if (dir) {
                        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    } else {
                        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    }
                    if (chooser.showDialog(panel, "open") != JFileChooser.APPROVE_OPTION) {
                        return;
                    }
                    textField.setText(chooser.getSelectedFile()
                            .getAbsolutePath());
                }
            });
            pathSelectors.addElement(this);
        }

        void doAction() {
            action.doIt(textField.getText());
        }

    }

    abstract class PathSelectorAction {
        abstract void doIt(String text);
    }

}
