/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/03/24, 12:03
!  AUTHOR(S): KOGA, Junichiro
!  File : DynmDiffPanel.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.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;

import ciss.phase_viewer.atomcoord.AtomCoords;
import ciss.phase_viewer.atomcoord.AtomList;
import ciss.phase_viewer.atomcoord.Nfdynm2AtomCoords;
import ciss.phase_viewer.common.ChaseFileChooser;
import ciss.phase_viewer.common.ConstParameters;
import ciss.phase_viewer.mainpanel.DefaultInternalFrameChase;
import ciss.phase_viewer.mainpanel.InternalFrameChase;

/**
 * 乽擇偮偺F_DYNM僼傽僀儖偺撪梕傪斾妑偡傞憖嶌乿傪峴偆GUI
 * 
 * @author
 */
public class DynmDiffPanel extends InternalFrameChase {
    private Logger logger = Logger.getLogger(DynmDiffPanel.class.getName());
    private String fromFile = "";
    private String toFile = "";
    private int toIndex = -1;
    private int fromIndex = 0;

    /** Creates a new instance of DynmDiffPanel */
    public DynmDiffPanel() {
        this("", "");
    }

    public DynmDiffPanel(String fromFile) {
        this(fromFile, "");
    }

    public DynmDiffPanel(String fromFile, String toFile) {
        super("compare two F_DYNM files", true, true, true, true,
                new Dimension(350, 200));
        this.fromFile = fromFile;
        this.toFile = toFile;
        init();
    }

    public DynmDiffPanel(String fromFile, String toFile, int fromIndex,
            int toIndex) {
        super("compare two F_DYNM files", true, true, true, true,
                new Dimension(350, 200));
        this.fromFile = fromFile;
        this.toFile = toFile;
        this.fromIndex = fromIndex;
        this.toIndex = toIndex;
        init();
    }

    private FileChooser from;
    private FileChooser to;

    private void init() {
        Container container = getContentPane();
        container.setLayout(new BorderLayout());
        from = new FileChooser("from", fromFile, String.valueOf(fromIndex));
        to = new FileChooser("to", toFile, String.valueOf(toIndex));
        JPanel p1 = new JPanel();
        p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
        p1.add(from);
        p1.add(to);
        container.add(p1, BorderLayout.NORTH);

        JButton ok = new JButton("ok");
        JButton can = new JButton("cancel");
        JPanel p2 = new JPanel();
        p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS));
        p2.add(ok);
        p2.add(can);
        JPanel pp = new JPanel();
        pp.add(p2);
        container.add(pp, BorderLayout.SOUTH);
        can.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                dispose();
            }
        });
        ok.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                doIt();
            }
        });
    }

    private void doIt() {
        String fromFile = from.getFileName();
        String toFile = to.getFileName();
        int fromFrame = from.getFrameNum();
        int toFrame = to.getFrameNum();
        Nfdynm2AtomCoords fromParser = new Nfdynm2AtomCoords(fromFile);
        Nfdynm2AtomCoords toParser = new Nfdynm2AtomCoords(toFile);
        AtomCoords fromCoords = null;
        AtomCoords toCoords = null;
        fromCoords = fromParser.getFrameAt(fromFrame);
        toCoords = toParser.getFrameAt(toFrame);
        fromCoords.isCart(true);
        toCoords.isCart(true);
        fromCoords.convert(AtomCoords.TO_INTERNAL, AtomCoords.TO_ANG);
        toCoords.convert(AtomCoords.TO_INTERNAL, AtomCoords.TO_ANG);

        AtomList fromList = fromCoords.getAtomList();
        AtomList toList = toCoords.getAtomList();

        double[][] fromCell = fromCoords.getCellDouble(0);
        double[][] toCell = fromCoords.getCellDouble(0);

        for (int i = 0; i < 3; i++) {
            logger.debug("from cell : " + fromCell[i][0] + " " + fromCell[i][1]
                    + " " + fromCell[i][2]);
            logger.debug("to cell : " + toCell[i][0] + " " + toCell[i][1] + " "
                    + toCell[i][2]);
        }

        for (int i = 0; i < fromList.size(); i++) {
            logger.debug("from atom, no. " + i + ": " + fromList.getAtomAt(i));
        }

        for (int i = 0; i < toList.size(); i++) {
            logger.debug("to atom, no. " + i + ": " + toList.getAtomAt(i));
        }

        int numcomp = fromList.size();
        if (numcomp > toList.size()) {
            numcomp = toList.size();
        }

        double cellxh = 0.5;
        double cellyh = 0.5;
        double cellzh = 0.5;
        String LS = System.getProperty("line.separator");
        String result = "#units : Angstrom" + LS;
        result += "#index element 儮x 儮y 儮z 儮d" + LS;
        DecimalFormat format = ConstParameters.formater_smaller_digits;
        for (int i = 0; i < numcomp; i++) {
            double[] fromPos = fromList.getAtomAt(i).getDouble();
            double[] toPos = toList.getAtomAt(i).getDouble();
            double diffx = fromPos[0] - toPos[0];
            double diffy = fromPos[1] - toPos[1];
            double diffz = fromPos[2] - toPos[2];
            if (diffx > cellxh) {
                diffx -= cellxh;
            } else if (diffx < -cellxh) {
                diffx += cellxh;
            }
            if (diffy > cellyh) {
                diffy -= cellyh;
            } else if (diffy < -cellyh) {
                diffy += cellyh;
            }
            if (diffz > cellzh) {
                diffz -= cellzh;
            } else if (diffz < -cellzh) {
                diffz += cellzh;
            }
            double x = toCell[0][0] * diffx + toCell[1][0] * diffy
                    + toCell[2][0] * diffz;
            double y = toCell[0][1] * diffx + toCell[1][1] * diffy
                    + toCell[2][1] * diffz;
            double z = toCell[0][2] * diffx + toCell[1][2] * diffy
                    + toCell[2][2] * diffz;
            result += Integer.toString(i + 1)
                    + " "
                    + fromList.getAtomAt(i).getElementName()
                    + " "
                    + format.format(x)
                    + " "
                    + format.format(y)
                    + " "
                    + format.format(z)
                    + " "
                    + format.format(Math.sqrt(Math.pow(x, 2.0)
                            + Math.pow(y, 2.0) + Math.pow(z, 2.0))) + LS;
        }
        JTextPane pane = new JTextPane();
        pane.setText(result);
        JScrollPane scrpane = new JScrollPane(pane);
        DefaultInternalFrameChase def = new DefaultInternalFrameChase("result",
                new Dimension(300, 500));
        def.getContentPane().add(scrpane);
    }

    class FileChooser extends JPanel {
        private JTextField textField;
        private JTextField frameNum;
        private JButton chooser;
        private String initFile = "";
        private String index = "0";

        FileChooser(String title, String initFile, String index) {
            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
            setBorder(new TitledBorder(title));
            this.initFile = initFile;
            this.index = index;
            ini();
        }

        private void ini() {
            textField = new JTextField(10);
            textField.setText(initFile);
            frameNum = new JTextField(5);
            frameNum.setText(index);
            chooser = new JButton("choose");
            add(textField);
            add(frameNum);
            add(chooser);
            chooser.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    bootChooser();
                }
            });
        }

        private int getFrameNum() {
            int ret = 0;
            try {
                ret = Integer.parseInt(frameNum.getText());
            } catch (Exception exc) {
            }
            return ret;
        }

        private String getFileName() {
            return textField.getText();
        }

        private void bootChooser() {
            ChaseFileChooser chooser = new ChaseFileChooser(
                    ChaseFileChooser.atom, true);

            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            if (chooser.showDialog(this, "select F_DYNM file") != JFileChooser.APPROVE_OPTION) {
                logger.info("canceled");
                return;
            }
            String selected = chooser.getSelectedFile().getAbsolutePath();
            textField.setText(selected);
        }
    }
}
