/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/02/08, 14:37
!  AUTHOR(S): KOGA, Junichiro
!  File : AnimDynmPlPanel.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.Dimension;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ExternalProgramExecuter;
import ciss.phase_viewer.common.ExternalProgramPanel;
import ciss.phase_viewer.common.Utils;

/**
 * animate.pl, dynm2tr2.plスクリプトを制御するGUI
 * 
 * @author
 */
public class AnimDynmPlPanel extends ExternalProgramPanel {
    private Logger logger = Logger.getLogger(AnimDynmPlPanel.class.getName());
    private String modeData;
    private String scriptName = "animate.pl";
    private String[] comp = { "mode_\\d+.tr2", "grid.mol2" };

    /**
     * @param dir
     *            ベースとなるディレクトリー
     * @param modeData
     *            F_MODEないしF_DYNMファイルのファイル名
     */
    public AnimDynmPlPanel(String dir, String modeData) {
        super("run animate.pl", dir, new Dimension(300, 200));
        this.modeData = modeData;
        init();
    }

    /**
     * @param dir
     *            ベースとなるディレクトリー
     * @param modeData
     *            F_MODEないしF_DYNMファイルのファイル名
     * @param scriptName
     *            スクリプトの名前; defaultはanimate.pl
     * @param comp
     *            ポスト処理でdirにファイルを移す際に「どのファイルを移すか」を表すフィルター(String#
     *            matchesメソッドで判定する).
     */
    public AnimDynmPlPanel(String dir, String modeData, String scriptName,
            String[] comp) {
        super("run " + scriptName, dir, new Dimension(300, 200));
        this.modeData = modeData;
        this.scriptName = scriptName;
        this.comp = comp;
        init();
    }

    private void init() {
        String ctrinp = baseDir + FS + "control.inp";
        if (new File(ctrinp).exists()) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(ctrinp));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    logger.debug("line: " + line);
                    if (line.trim().startsWith("origin")) {
                        String[] origs = line.split("\\s+");
                        if (origs.length >= 4) {
                            origx.setText(origs[1]);
                            origy.setText(origs[2]);
                            origz.setText(origs[3]);
                        }
                    }
                    if (line.trim().startsWith("vector1")) {
                        String[] vec1 = line.split("\\s+");
                        if (vec1.length >= 4) {
                            vec1x.setText(vec1[1]);
                            vec1y.setText(vec1[2]);
                            vec1z.setText(vec1[3]);
                        }
                    }
                    if (line.trim().startsWith("vector2")) {
                        String[] vec2 = line.split("\\s+");
                        if (vec2.length >= 4) {
                            vec2x.setText(vec2[1]);
                            vec2y.setText(vec2[2]);
                            vec2z.setText(vec2[3]);
                        }
                    }
                    if (line.trim().startsWith("vector3")) {
                        String[] vec3 = line.split("\\s+");
                        if (vec3.length >= 4) {
                            vec3x.setText(vec3[1]);
                            vec3y.setText(vec3[2]);
                            vec3z.setText(vec3[3]);
                        }
                    }
                }
            } catch (Exception exc) {
            } finally {
                try {
                    reader.close();
                } catch (Exception exc) {
                }
            }
        }
    }

    private JTextField origx;
    private JTextField origy;
    private JTextField origz;
    private JTextField vec1x;
    private JTextField vec1y;
    private JTextField vec1z;
    private JTextField vec2x;
    private JTextField vec2y;
    private JTextField vec2z;
    private JTextField vec3x;
    private JTextField vec3y;
    private JTextField vec3z;

    public JPanel createMainPanel() {
        JPanel ret = new JPanel();
        ret.setLayout(new BoxLayout(ret, BoxLayout.Y_AXIS));
        ret.setBorder(new TitledBorder("control.inp"));
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(1, 4));
        p1.add(new JLabel("origin"));
        origx = new JTextField(5);
        origy = new JTextField(5);
        origz = new JTextField(5);
        p1.add(origx);
        p1.add(origy);
        p1.add(origz);

        JPanel p2 = new JPanel();
        p2.setLayout(new GridLayout(1, 4));
        p2.add(new JLabel("vector1"));
        vec1x = new JTextField(5);
        vec1y = new JTextField(5);
        vec1z = new JTextField(5);
        p2.add(vec1x);
        p2.add(vec1y);
        p2.add(vec1z);

        JPanel p3 = new JPanel();
        p3.setLayout(new GridLayout(1, 4));
        p3.add(new JLabel("vector2"));
        vec2x = new JTextField(5);
        vec2y = new JTextField(5);
        vec2z = new JTextField(5);
        p3.add(vec2x);
        p3.add(vec2y);
        p3.add(vec2z);

        JPanel p4 = new JPanel();
        p4.setLayout(new GridLayout(1, 4));
        p4.add(new JLabel("vector3"));
        vec3x = new JTextField(5);
        vec3y = new JTextField(5);
        vec3z = new JTextField(5);
        p4.add(vec3x);
        p4.add(vec3y);
        p4.add(vec3z);

        ret.add(p1);
        ret.add(p2);
        ret.add(p3);
        ret.add(p4);

        return ret;
    }

    public boolean createExeString() {
        String anim = getPerlScript(scriptName);
        String controlinp = "";
        String origin = null;
        String vector1 = null;
        String vector2 = null;
        String vector3 = null;
        try {
            String ox = origx.getText();
            String oy = origy.getText();
            String oz = origz.getText();
            if (ox.length() != 0 && oy.length() != 0 && oz.length() != 0) {
                origin = "origin " + ox + " " + oy + " " + oz;
            }
            String ve1x = vec1x.getText();
            String ve1y = vec1y.getText();
            String ve1z = vec1z.getText();
            if (ve1x.length() != 0 && ve1y.length() != 0 && ve1z.length() != 0) {
                vector1 = "vector1 " + ve1x + " " + ve1y + " " + ve1z;
            }
            String ve2x = vec2x.getText();
            String ve2y = vec2y.getText();
            String ve2z = vec2z.getText();
            if (ve2x.length() != 0 && ve2y.length() != 0 && ve2z.length() != 0) {
                vector2 = "vector2 " + ve2x + " " + ve2y + " " + ve2z;
            }
            String ve3x = vec3x.getText();
            String ve3y = vec3y.getText();
            String ve3z = vec3z.getText();
            if (ve3x.length() != 0 && ve3y.length() != 0 && ve3z.length() != 0) {
                vector3 = "vector3 " + ve3x + " " + ve3y + " " + ve3z;
            }
        } catch (Exception exc) {
        }
        String str = "";
        String LS = System.getProperty("line.separator");
        if (origin != null) {
            str += origin + LS;
        }
        if (vector1 != null && vector2 != null && vector3 != null) {
            str += vector1 + LS;
            str += vector2 + LS;
            str += vector3;
        }
        if (str.trim().length() != 0) {
            controlinp = baseDir + System.getProperty("file.separator")
                    + "control.inp";
            BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new FileWriter(controlinp));
                writer.write(str, 0, str.length());
            } catch (Exception exc) {
                logger.error("failed creation of control.inp");
                controlinp = "";
            } finally {
                try {
                    writer.close();
                } catch (Exception exc) {
                }
            }
        }
        if (controlinp.length() != 0) {
            exeString = anim + " " + Utils.getPathDQ(baseDir + FS + modeData)
                    + " " + Utils.getPathDQ(controlinp);
        } else {
            exeString = anim + " " + Utils.getPathDQ(baseDir + FS + modeData);
        }
        return true;
    }

    public void bootPostProcess() {
        String moveToDir = baseDir;
        String moveFromDir = System.getProperty("user.dir");
        String[] files = new File(moveFromDir).list();
        if (files == null || files.length == 0) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            for (int j = 0; j < comp.length; j++) {
                if (files[i].matches(comp[j])) {
                    String moveFromFile = moveFromDir + FS + files[i];
                    String moveToFile = moveToDir + FS + files[i];
                    if (moveToFile.trim().equalsIgnoreCase(moveToFile.trim())) {
                        ExternalProgramExecuter.remove(moveToFile);
                    }
                    ExternalProgramExecuter.move(moveFromFile, moveToFile);
                }
            }
        }
    }

}
