/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on ----
!  AUTHOR(S): KOGA, Junichiro
!  File : DosPlPanel.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.plugins.projectmanipulator.phase.resultsviewerpanel.tools;

import java.awt.GridLayout;
import java.io.File;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ExternalProgramPanel;
import ciss.phase_viewer.common.InputPanel;
import ciss.phase_viewer.common.MyMessageBox;
import ciss.phase_viewer.common.Utils;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

public class DosPlPanel extends ExternalProgramPanel {
    private Logger logger = Logger.getLogger(DosPlPanel.class.getName());

    /** project directory */
    private String projdir;

    /** name of dos.data */
    private String dosData;

    /*
     * panel elements
     */
    private JComboBox cbMode;

    private InputPanel iperangemin;

    private InputPanel iperangemax;

    private InputPanel ipdosmin;

    private InputPanel ipdosmax;

    private InputPanel ipeinc;

    private InputPanel ipdosinc;

    private JCheckBox cbwithfermi;

    private JCheckBox cbcolor;

    private InputPanel ipfont;

    private InputPanel ipwidth;

    private InputPanel iptitle;

    private String FS = System.getProperty("file.separator");

    private MyMessageBox mbox = new MyMessageBox();

    /**
     * このパネルのタイトルのみを引数とした, シンプルなコンストラクター.
     * 
     * @param title
     *            このパネルの上部に表示される文字列を指定.
     */
    public DosPlPanel(String title) {
        super(title, new java.awt.Dimension(400, 300));
    }

    /**
     * プロジェクトディレクトリーへのフルパスを設定する.
     * 
     * @param projdir
     *            プロジェクトディレクトリーのフルパス.
     */
    public void setProjDir(String projdir) {
        this.projdir = projdir;
        setCurrDir(projdir);
    }

    /**
     * 状態密度ファイルのファイル名を設定するメソッド.
     * 
     * @param dosData
     *            状態密度情報ファイルのファイル名.
     */
    public void setDosData(String dosData) {
        this.dosData = dosData;
    }

    /**
     * perlスクリプト実行用の文字列を作成するクラス. まずカレントディレクトリーの書き込み許可の有無を調べ,
     * 書き込める場合はパネルに入力された情報を元に実行用の文字列を作成する. この際, Windowsと他のOSで扱いが異なる点に注意.
     * Windowsの場合#!/usr/bin/perlなどとファイルの先頭に書いても executableにはならないようなので,
     * 直接perlインタープリターを 呼ぶことによって実現している.
     * 
     * @return 成功の場合真を返す. dos.plが見つからない, などの事情がある場合は falseを返す.
     */
    public boolean createExeString() {
        GlobalProperties pm = PropertiesManager
                .getGlobalProperties(PropertiesManager.PROPERTIES_PVIEWER);

        String curDir = System.getProperty("user.dir");
        if (!(new File(curDir)).canWrite()) {
            mbox.setText("can't create tmp file ... check permission.");
            return false;
        }

        String dospl = new String();

        dospl = System.getProperty("pviewer.home") + FS
                + pm.getProperty("phasetoolsdir") + FS + "dos.pl";

        logger.debug("dos.pl: " + dospl);
        if (!((new File(dospl)).exists())) {
            exeString = "dos.pl";
            mbox.setText("could not find dos.pl");
            return false;
        }

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

        exeString = dospl + " " + Utils.getPathDQ(projdir + dosData) + " ";

        /* set options */
        String mode = (String) cbMode.getSelectedItem();
        String dosrangemin = ipdosmin.getValue();
        String dosrangemax = ipdosmax.getValue();
        String dosinc = ipdosinc.getValue();
        String font = ipfont.getValue();
        String title = iptitle.getValue();

        String erangemin = iperangemin.getValue();
        String erangemax = iperangemax.getValue();
        String einc = ipeinc.getValue();
        boolean fermi = cbwithfermi.isSelected();
        boolean color = cbcolor.isSelected();
        String width = ipwidth.getValue();

        if (mode.trim().length() != 0) {
            exeString = exeString + " -mode=" + mode;
        }
        if (erangemin.trim().length() != 0 && erangemax.trim().length() != 0) {
            exeString = exeString + " -erange=" + erangemin + "," + erangemax;
        }
        if (dosrangemin.trim().length() != 0
                && dosrangemax.trim().length() != 0) {
            exeString = exeString + " -dosrange=" + dosrangemin + ","
                    + dosrangemax;
        }

        if (einc.trim().length() != 0) {
            exeString = exeString + " -einc=" + einc;
        }
        if (dosinc.trim().length() != 0) {
            exeString = exeString + " -dosinc=" + dosinc;
        }
        if (font.trim().length() != 0) {
            exeString = exeString + " -font=" + font;
        }
        if (title.trim().length() != 0) {
            exeString = exeString + " -title=" + title;
        }
        if (fermi) {
            exeString = exeString + " -with_fermi";
        }
        if (width.trim().length() != 0) {
            exeString = exeString + " -width=" + width;
        }
        if (color) {
            exeString = exeString + " -color";
        }

        logger.debug(exeString);

        return true;
    }

    /**
     * perlスクリプトを実行した後のポスト処理を行う. 具体的には, カレントディレクトリーにあるepsファイルを
     * プロジェクトディレクトリーへ移す操作を行う.
     */
    public void bootPostProcess() {
        // String total_file = "density_of_states.eps";
        // String layer_file = "dos_l\\d+.eps";
        // String ados_file = "dos_a\\d+.eps";
        // String pdos_file = "dos_a\\d+l\\d+m\\d+t\\d+.eps";
        // Vector moveToVector = new Vector();
        // File proj = new File(System.getProperty("user.dir"));
        // String [] files = proj.list();
        // if ( files == null || files.length == 0 ) {
        // return;
        // }
        // for ( int i=0 ; i<files.length ; i++ ) {
        // if ( files[i].matches(total_file) || files[i].matches(layer_file) ||
        // files[i].matches(ados_file) || files[i].matches(pdos_file) ) {
        // moveToVector.addElement(files[i]);
        // }
        // }
        //
        // if ( moveToVector.size() == 0 ) {
        // return;
        // }
        // String moveToDir = projdir;
        // for ( int i=0 ; i<moveToVector.size() ; i++ ) {
        // String moveToPath = projdir + (String) moveToVector.elementAt(i);
        // String moveFromPath =
        // System.getProperty("user.dir")+System.getProperty("file.separator")+(String)
        // moveToVector.elementAt(i);
        // if ( !moveFromPath.trim().equalsIgnoreCase(moveToPath.trim()) ) {
        // ExternalProgramExecuter.remove(moveToPath);
        // }
        // }
        // try{
        // Thread.sleep(100);
        // } catch(Exception e) {}
        //
        // for ( int i=0 ; i<moveToVector.size() ; i++ ) {
        // String moveToPath = projdir + (String) moveToVector.elementAt(i);
        // String moveFromPath =
        // System.getProperty("user.dir")+System.getProperty("file.separator")+(String)
        // moveToVector.elementAt(i);
        // ExternalProgramExecuter.move(moveFromPath,moveToPath);
        // }
    }

    /**
     * このGUIの大元のパネルを作成するメソッド.
     * 
     * @return このパネルの各パーツを配備したJPanel.
     */
    public JPanel createMainPanel() {
        JPanel p = new JPanel();
        p.setLayout(new GridLayout(3, 4));
        p.setBorder(new TitledBorder("options"));

        String[] modeString = { "total", "atom", "layer", "projected" };
        JPanel modePanel = new JPanel();
        modePanel.setBorder(new TitledBorder("mode"));
        cbMode = new JComboBox(modeString);
        modePanel.add(cbMode);

        iperangemin = new InputPanel("erange(min)", 0, 7, true);
        iperangemax = new InputPanel("erange(max)", 0, 7, true);
        ipdosmin = new InputPanel("dosrange(min)", 0, 7, true);
        ipdosmax = new InputPanel("dosrange(max)", 0, 7, true);

        ipeinc = new InputPanel("einc", 0, 7, true);
        ipdosinc = new InputPanel("dosinc", 0, 7, true);

        cbwithfermi = new JCheckBox("with_fermi");
        cbcolor = new JCheckBox("color");
        ipwidth = new InputPanel("width", 0, 7, true);

        ipfont = new InputPanel("font", 0, 7, true);

        iptitle = new InputPanel("title", 0, 7, true);

        p.add(modePanel);
        p.add(ipwidth);
        p.add(cbwithfermi);
        p.add(cbcolor);

        p.add(iperangemin);
        p.add(iperangemax);
        p.add(ipdosmin);
        p.add(ipdosmax);

        p.add(ipeinc);
        p.add(ipdosinc);
        p.add(ipfont);
        p.add(iptitle);

        return p;
    }
}
