/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2007/03/27 19:31:06
!  AUTHOR(S): KOGA, Junichiro
!  File : PerlScript.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.primitiveguis.perlscriptexecuters;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.Vector;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ExternalProgramExecuter;
import ciss.phase_viewer.common.Utils;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

/**
 * PHASEなどに付属するPerlスクリプトの「実行方法」をカプセル化したクラス
 * 
 * @author jkoga
 * 
 */
public class PerlScript {
    private Logger logger = Logger.getLogger(PerlScript.class.getName());

    private String scriptFile;

    private Vector options;

    private File workDir;

    /**
     * 
     * @param scriptFile
     *            走らせたいスクリプトのファイルの名
     * @param workDir
     *            作業ディレクトリー
     */
    public PerlScript(String scriptFile, File workDir) {
        this.scriptFile = scriptFile;
        this.workDir = workDir;
    }

    /**
     * オプションを設定する.
     * 
     * @param option
     */
    public void addOptions(PerlScriptOption option) {
        if (options == null)
            options = new Vector();
        options.addElement(option);
    }

    public PerlScriptOption[] getOptions() {
        PerlScriptOption[] opts = new PerlScriptOption[options.size()];
        options.copyInto(opts);
        return opts;
    }

    private String[] command;

    /**
     * "コマンド"を設定する。基本的にはperlスクリプトに渡したい文字列の配列だけど、オプションを設定したい個所はPerlScriptOption.
     * OPTIONSとしておく. オプションは固めて定義されていることを期待している。
     * 
     * @param command
     *            上記のようなコマンド
     */
    public void setCommand(String[] command) {
        this.command = command;
    }

    protected BufferedReader[] exec() {
        String com = getPerlScript(scriptFile);
        for (int i = 0; i < command.length; i++) {
            if (command[i].equals(PerlScriptOption.OPTION)) {
                for (int j = 0; j < options.size(); j++) {
                    PerlScriptOption opt = (PerlScriptOption) options.get(j);
                    com += " " + opt.generateOptions();
                }
            } else {
                com += " " + command[i];
            }
        }

        logger.info("executing: " + com);

        BufferedReader[] ret = null;
        try {
            ret = ExternalProgramExecuter.executeGetBR(com, workDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * perlスクリプトのパスを取得; windowsの場合perl phasetoolsdir\\name,
     * Unixの場合phasetoolsdir/name
     * 
     * @param name
     *            スクリプトの名前 return perlスクリプト
     */
    private 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;
    }
}
