/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/10/16, 17:23
!  AUTHOR(S): KOGA, Junichiro
!  File : PhaseInputChecker.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.input;

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

import org.apache.log4j.Logger;

import ciss.phase_viewer.inputinterface.Input;
import ciss.phase_viewer.inputinterface.InputInterface;
import ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeEvent;
import ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeListener;
import ciss.phase_viewer.inputinterface.InputInterfacePrimitiveEntry;

/**
 * PHASE用のInputCheckerのベースクラス...
 * 
 * @author
 */
public abstract class PhaseInputChecker implements InputChecker,
        InputInterfaceEntryChangeListener {
    private Logger logger = Logger.getLogger(PhaseInputChecker.class.getName());

    protected InputInterface inputInterface;

    /*
     * (non-Javadoc)
     * 
     * @see ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeListener#
     * inputInterfaceEntryChanged
     * (ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeEvent)
     */
    public void inputInterfaceEntryChanged(InputInterfaceEntryChangeEvent e) {
    }

    /*
     * (non-Javadoc)
     * 
     * @see ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeListener#
     * inputInterfaceInitialized()
     */
    public void inputInterfaceInitialized() {
    }

    /*
     * (non-Javadoc)
     * 
     * @see ciss.phase_viewer.inputinterface.InputInterfaceEntryChangeListener#
     * inputInterfaceInitializing()
     */
    public void inputInterfaceInitializing() {
    }

    protected String fileNamesData;

    protected String candidate = "";

    protected String message = "";

    protected String LS = System.getProperty("line.separator");

    protected int state = OK;

    public PhaseInputChecker() {
    }

    /*
     * (non-Javadoc)
     * 
     * @see ciss.phase_viewer.input.InputChecker#getCurrentState()
     */
    public int getCurrentState() {
        return state;
    }

    /*
     * (non-Javadoc)
     * 
     * @see ciss.phase_viewer.input.InputChecker#getMessage()
     */
    public String getMessage() {
        return message;
    }

    /**
     * InputInterfacePrimitiveEntryを修正する.
     * 
     * @param blockTag
     *            ブロックのタグ
     * @param entryTag
     *            エントリーのタグ
     * @param value
     *            この値に修正する
     * @param unit
     *            この単位に修正する
     */
    protected void fixPrimitiveEntry(String blockTag, String entryTag,
            String value, String unit) {
        inputInterface.selectRoot();
        inputInterface.selectBlock(blockTag);
        InputInterfacePrimitiveEntry prim = inputInterface
                .getPrimitiveEntry(entryTag);
        prim.setValue(value);
        prim.setUnit(unit);
        inputInterface.replaceEntry(prim, this);
        state = OK;
    }

    /**
     * 指定の識別子のファイルのパスを取得. 識別子が見つからない場合, nullを返す.
     * 
     * @param ident
     *            識別子
     * @return identに対応するファイルのパス. 識別子が見つからない場合null.
     */
    protected String getFilePath(String ident) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(fileNamesData));
            String line = "";
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("&") || line.startsWith("/"))
                    continue;
                if (line.startsWith(ident)) {
                    String[] ar = line.split("=");
                    String path = ar[1].trim().replaceAll("'", "");
                    File file = new File(path);
                    if (file.isAbsolute())
                        return path;

                    String tmp = new File(inputInterface.getFileName())
                            .getParent()
                            + System.getProperty("file.separator")
                            + path;
                    return tmp;
                }
            }
        } catch (Exception exc) {
        } finally {
            try {
                reader.close();
            } catch (Exception exc) {
            }
        }
        return null;
    }

    /**
     * 指定の識別子のファイルを全て取得する. 識別子が見つからない場合nullを返す.
     * 
     * @param ident
     *            識別子
     * @return identに対応するファイルのパス; 識別子が見つからない場合null.
     */
    protected String[] getAllFilePath(String ident) {
        BufferedReader reader = null;
        Vector retvec = new Vector();
        try {
            reader = new BufferedReader(new FileReader(fileNamesData));
            String line = "";
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("&") || line.startsWith("/"))
                    continue;
                if (line.startsWith(ident)) {
                    String[] ar = line.split("=");
                    String path = ar[1].trim().replaceAll("'", "");
                    File file = new File(path);
                    if (file.isAbsolute())
                        retvec.addElement(path);

                    String tmp = new File(inputInterface.getFileName())
                            .getParent()
                            + System.getProperty("file.separator")
                            + path;
                    retvec.addElement(tmp);
                }
            }
        } catch (Exception exc) {
        } finally {
            try {
                reader.close();
            } catch (Exception exc) {
            }
        }

        if (retvec.size() == 0)
            return null;

        String[] ret = new String[retvec.size()];
        retvec.copyInto(ret);
        return ret;
    }

    protected String projDir;

    public void setInput(Input input) {
        if (!(input instanceof InputInterface)) {
            logger.error("invalid input ...");
            return;
        }
        this.inputInterface = (InputInterface) input;
        this.projDir = new File(inputInterface.getFileName()).getParent();
        fileNamesData = this.projDir + System.getProperty("file.separator")
                + "file_names.data";
    }

}
