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

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

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

import ciss.phase_viewer.main.PluginLoader;
import ciss.phase_viewer.scripting.ScriptWrapper;

/**
 * スクリプトの中の文字列を, 環境に応じて書き換えたい場合がしばしばあるよね. このクラスを継承したクラスは,
 * そのための規則をインプリメントしないといけない.
 * 
 * @author
 */
public class ScriptKeywordsReplacer {
    public static final String REPLACED_FILE_PREFIX = "__";

    private final String props = "/ciss/phase_viewer/scripting/scriptreplace/rules.properties";
    private Vector rules;

    private Logger logger = Logger.getLogger(ScriptKeywordsReplacer.class
            .getName());

    public ScriptKeywordsReplacer() {
        rules = new Vector();
        Properties properties = ciss.phase_viewer.common.Utils
                .getPropertiesFrom(props);
        if (properties != null) {
            Enumeration enumeration = properties.propertyNames();
            while (enumeration.hasMoreElements()) {
                String loadClass = properties.getProperty(enumeration
                        .nextElement().toString());
                ScriptReplaceRules rule = (ScriptReplaceRules) PluginLoader
                        .instantiate(loadClass, null);
                rules.addElement(rule);
            }
        }

    }

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

    public boolean replace(ScriptWrapper script, Document document,
            boolean overwrite) {
        if (rules.size() == 0) {
            return false;
        }
        String scriptText = ciss.phase_viewer.common.Utils
                .getStringFromFile(script.getPath());
        for (int i = 0; i < rules.size(); i++) {
            scriptText = ((ScriptReplaceRules) rules.get(i)).replace(
                    scriptText, document, overwrite);
            logger.debug("applying replace rule: "
                    + rules.get(i).getClass().getName());
            if (scriptText == null) {
                return false;
            }
        }

        createNewScript(script.getPath(), scriptText, overwrite);
        return true;
    }

    /**
     * 置換された文字列をファイルに書き込む。
     * 
     * @param file
     *            書き出し先のファイル
     * @param script
     *            スクリプトそのもの
     * @param overwrite
     *            真のときは上書き, そうでないときはファイル名に'__'がつく.
     */
    protected void createNewScript(String file, String script, boolean overwrite) {
        String dir = new File(file).getParent();
        File newfile = new File(file);
        if (!overwrite) {
            newfile = new File(dir + System.getProperty("file.separator")
                    + ScriptKeywordsReplacer.REPLACED_FILE_PREFIX
                    + new File(file).getName());
        }
        newfile.delete();

        if (ScriptWrapper.getTypeFromFile(newfile.getName()).equals(
                ScriptWrapper.BSH)) {
            script = script.replaceAll("\\\\", "\\\\\\\\");
        }

        BufferedWriter bwriter = null;
        try {
            bwriter = new BufferedWriter(new FileWriter(newfile));
            bwriter.write(script, 0, script.length());
            bwriter.flush();
        } catch (IOException ioe) {
            logger.error("failed to create new script");
            ioe.printStackTrace();
        } finally {
            try {
                bwriter.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

}
