/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on ----
!  AUTHOR(S): KOGA, Junichiro
!  File : ExternalProgramPanel.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.common;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

import org.apache.log4j.Logger;

import ciss.phase_viewer.mainpanel.InternalFrameChase;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

//public abstract class ExternalProgramPanel extends JInternalFrame {
public abstract class ExternalProgramPanel extends InternalFrameChase {
    private Logger logger = Logger.getLogger(ExternalProgramPanel.class
            .getName());

    /** content pane */
    private Container cont;

    /** ok button */
    private JButton btnok;

    /** cancel button */
    private JButton btncancel;

    /** string to execute */
    protected String exeString = new String();

    /** file separator */
    protected final String FS = System.getProperty("file.separator");

    /** the 'base directory' */
    protected String baseDir;

    /** button panel */
    private JPanel pbutton;

    private MyMessageBox mbox = new MyMessageBox();

    /**
     * GUIの雛形を作成する
     */
    public ExternalProgramPanel(String title) {
        super(title, true, true, true, true);
        cont = getContentPane();
        cont.setLayout(new BoxLayout(cont, BoxLayout.Y_AXIS));
        cont.add(createMainPanel());
        cont.add(createButtonPanel());
    }

    public ExternalProgramPanel(String title, java.awt.Dimension size) {
        super(title, true, true, true, true, size);
        cont = getContentPane();
        cont.setLayout(new BoxLayout(cont, BoxLayout.Y_AXIS));
        cont.add(createMainPanel());
        cont.add(createButtonPanel());
    }

    public ExternalProgramPanel(String title, String baseDir,
            java.awt.Dimension size) {
        super(title, true, true, true, true, size);
        this.baseDir = baseDir;
        cont = getContentPane();
        cont.setLayout(new BoxLayout(cont, BoxLayout.Y_AXIS));
        cont.add(createMainPanel());
        cont.add(createButtonPanel());
    }

    /**
     * 実行する外部プログラムのパスの取得
     * 
     * @return 外部プログラムへのパス.
     */
    public String getExeString() {
        return this.exeString;
    }

    /**
     * 実行する外部プログラムのパスを設定する.
     * 
     * @param exeString
     *            外部プログラムへのパス.
     */
    public void setExeString(String exeString) {
        this.exeString = exeString;
    }

    private String currDir = System.getProperty("user.dir");

    /**
     * 作業ディレクトリーをセット. デフォルトは"user.dir"
     * 
     * @param currDir
     *            作業ディレクトリー
     */
    protected void setCurrDir(String currDir) {
        this.currDir = currDir;
    }

    /** create the button Panel */
    private JPanel createButtonPanel() {
        pbutton = new JPanel();
        pbutton.setLayout(new FlowLayout());
        btnok = new JButton("OK");
        btncancel = new JButton("cancel");
        pbutton.add(btnok);
        pbutton.add(btncancel);

        btnok.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!createExeString()) {
                    dispose();
                    return;
                }
                if (!bootExecuter()) {
                    dispose();
                    return;
                }
                bootPostProcess();
            }
        });

        btncancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        return pbutton;
    }

    /**
     * 外部プログラムを起動する.
     * 
     * @return 真なら起動に成功.
     */
    public boolean bootExecuter() {
        logger.info("executing: " + exeString);
        try {
            String str;
            BufferedReader[] br = ExternalProgramExecuter.executeGetBR(
                    exeString, new File(currDir));
            while ((str = br[0].readLine()) != null) {
                logger.info(str);
            }
            br[0].close();
            br[1].close();
            // MyThread thread = new MyThread(exeString);
        } catch (Exception e) {
            mbox.setText("failed execution of " + exeString);
            return false;
        }

        return true;
    }

    /**
     * 外部プログラム起動後に必ず呼ばれる. ポスト処理を 行いたい際にはオーバーライドする.
     */
    public void bootPostProcess() {
    }

    /**
     * 実行すべき外部プログラムのパスを作成するメソッド. このパネルで使用したい外部プログラムを作成するように オーバーライドする.
     * 
     * @return 作成に成功したら真
     */
    public abstract boolean createExeString();

    /**
     * このパネルのGUIの詳細を作成する.
     * 
     * @return 望みのGUIを配備したJPanel
     */
    public abstract JPanel createMainPanel();

    /**
     * perlスクリプトのパスを取得; windowsの場合perl phasetoolsdir\\name,
     * Unixの場合phasetoolsdir/name
     * 
     * @param name
     *            スクリプトの名前 return perlスクリプト
     */
    protected String getPerlScript(String name) {
        String ret = "";
        String FS = System.getProperty("file.separator");
        GlobalProperties pm = PropertiesManager
                .getGlobalProperties(PropertiesManager.PROPERTIES_PVIEWER);
        ret = System.getProperty("pviewer.home") + FS
                + pm.getProperty("phasetoolsdir") + FS + name;
        if (!((new File(ret)).exists())) {
            ret = name;
        }

        if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            ret = "perl.exe " + Utils.getPathDQ(ret);
        }
        return ret;
    }

}
