/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/01/06, 18:46
!  AUTHOR(S): KOGA, Junichiro
!  File : PhaseScriptReplaceRules.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;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;

import ciss.phase_viewer.common.Utils;
import ciss.phase_viewer.jdom.MyElement;
import ciss.phase_viewer.jobcontrol.JobController;
import ciss.phase_viewer.scripting.scriptreplace.ScriptReplaceRules;

/**
 * PHASE用スクリプトを, 実行前に整形する.
 * 
 */
public class PhaseScriptReplaceRules extends ScriptReplaceRules {
    private Logger logger = Logger.getLogger(PhaseScriptReplaceRules.class
            .getName());

    /** Creates a new instance of PhaseScriptReplaceRules */
    public PhaseScriptReplaceRules() {
    }

    private final String __PHASE__ = "__PHASE__";
    private final String __NE__ = "__NE__";
    private final String __NK__ = "__NK__";

    private final String __NE0__ = "__NE0__";
    private final String __NK0__ = "__NK0__";

    private String[] keys = { __NE__, __NK__, __PHASE__, __NE0__, __NK0__ };

    public String[] getKeys() {
        return keys;
    }

    public String replace(String file, org.jdom.Document document,
            boolean overwrite) {
        if (document == null || !document.hasRootElement()) {
            logger.error("invalid document");
            return null;
        }

        Element mpiParams = document.getRootElement().getChild("MPI_Params");
        if (mpiParams == null) {
            logger.warn("invalid mpiparams... using defaults");
        }

        Element jobcontrol = document.getRootElement().getChild(
                JobController.JOBCONTROL);
        if (jobcontrol == null) {
            logger.error("invalid jobcontrol element");
            return null;
        }

        Element targethost = jobcontrol.getChild("targethost");
        if (targethost == null) {
            logger.error("invalid 'targethost' element");
            return null;
        }

        Element env = targethost.getChild("env");
        if (env == null) {
            logger.error("invalid 'env' element");
            return null;
        }

        String[] keys = getKeys();

        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            if (key.equals(__PHASE__)) {
                String bindir = MyElement
                        .decode(env.getChildTextTrim("bindir"));
                String phase = bindir + "/phase";
                if (bindir == null || bindir.trim().length() == 0) {
                    phase = "phase";
                }
                if (targethost.getTextTrim().equals("localhost")
                        && System.getProperty("os.name").toLowerCase()
                                .startsWith("windows")) {
                    phase = Utils.escapeBackSlash(bindir) + "\\\\"
                            + "phase.exe";
                    if (bindir == null || bindir.trim().length() == 0) {
                        phase = "phase.exe";
                    }
                }
                file = file.replaceAll(key, phase);
            } else if (key.equals(__NK__) || key.equals(__NE__)) {
                String nn = "1";
                if (mpiParams != null) {
                    String test = "";
                    if (key.equals(__NK__)) {
                        test = "nk";
                    } else if (key.equals(__NE__)) {
                        test = "ne";
                    }
                    nn = MyElement.decode(mpiParams.getChildTextTrim(test));
                    try {
                        Integer.parseInt(nn);
                    } catch (Exception e) {
                        nn = "1";
                    }
                }
                if (!mpiSupport(env, targethost.getTextTrim()))
                    nn = "";
                file = file.replaceAll(key, nn);
            } else if (key.equals(__NK0__) || key.equals(__NE0__)) {
                String nn = "";
                if (mpiSupport(env, targethost.getTextTrim())) {
                    if (key.equals(__NK0__))
                        nn = "nk=";
                    if (key.equals(__NE0__))
                        nn = "ne=";
                }
                file = file.replaceAll(key, nn);

            }
        }

        if (!(targethost.getTextTrim().equals("localhost") && System
                .getProperty("os.name").toLowerCase().startsWith("windows"))) {
            file = file.replaceAll("\\r", "");
        }

        return file;
    }

    public String replace(String script, Document document) {
        return replace(script, document, false);
    }

}
