/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/01/19, 21:00
!  AUTHOR(S): KOGA, Junichiro
!  File : DynmImporter.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.atomcoord.io;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.HashMap;
import java.util.Vector;

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

import org.apache.log4j.Logger;

import ciss.phase_viewer.atomcoord.AtomCoords;
import ciss.phase_viewer.atomcoord.Nfdynm2AtomCoords;
import ciss.phase_viewer.mainpanel.ChaseProgressMonitor;
import ciss.phase_viewer.mainpanel.InternalFrameChase;

/**
 * PHASEの座標出力形式である,「F_DYNM」ファイルをインポートするクラス.
 * 
 * @author
 */
public class DynmImporter implements Importer {
    private Logger logger = Logger.getLogger(DynmImporter.class.getName());
    private String frame = FrameCombo.FIRST_FRAME;
    private Nfdynm2AtomCoords parser;
    private int target = 0;

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

    public ciss.phase_viewer.atomcoord.AtomCoords[] getAtomCoordsFrom(
            String fileName) {
        parser = new Nfdynm2AtomCoords(fileName);

        ChaseProgressMonitor monitor = ChaseProgressMonitor.getMonitor();
        monitor.setProgress(parser);

        int numFrame = parser.getNumFrames();
        int targetFrame = -1;
        if (select != null) {
            targetFrame = select.getTargetFrame(numFrame);
        }
        if (targetFrame < 0) {
            if (tfstart == null || tfend == null || tfgap == null)
                parser.setStartEndGap(0, numFrame - 1, 1);
            else
                try {
                    int istart = Integer.parseInt(tfstart.getText().trim());
                    int iend = Integer.parseInt(tfend.getText().trim());
                    int igap = Integer.parseInt(tfgap.getText().trim());
                    if (istart < 0 || igap > iend && iend >= 0) {
                        logger.error("invalid specifcation for the start, end or gap parameter");
                        logger.error("using the default values");
                    } else {
                        parser.setStartEndGap(istart, iend, igap);
                    }
                } catch (NumberFormatException nfe) {
                    logger.error("invalid specifcation for the start, end or gap parameter");
                    logger.error("using the default values");
                }
            Vector vec = parser.getFrames();
            AtomCoords[] cds = new AtomCoords[vec.size()];
            vec.copyInto(cds);
            return cds;
        }

        return new AtomCoords[] { parser.getFrameAt(targetFrame) };
    }

    public String getType() {
        return "F_DYNM file (phase)";
    }

    public javax.swing.filechooser.FileFilter getFileFilter() {
        return new DynmFileFilter();
    }

    public boolean hasOptions() {
        return true;
    }

    private PropertyChangeListener listener;

    public void createOptionsPanel(boolean isheavy,
            PropertyChangeListener listener, String fileName) {
        this.listener = listener;
        if (!isheavy) {
            OptionsPanel panel = new OptionsPanel(fileName);
        } else {
            OptionsPanelHeavy heavy = new OptionsPanelHeavy(fileName);
        }
    }

    private FrameCombo select;
    private JTextField tfstart;
    private JTextField tfend;
    private JTextField tfgap;

    public void setOptions(HashMap options) {
    }

    /**
     * もう面倒なので, "nfdynm.data"というファイル名のみaccept.
     */
    public boolean isImportable(String fileName) {
        if (new java.io.File(fileName).isDirectory()) {
            return false;
        }
        String fname = new java.io.File(fileName).getName();
        return fname.equals("nfdynm.data");
    }

    class OptionsPanelHeavy extends InternalFrameChase {
        OptionsPanelHeavy(String fileName) {
            super("options", new java.awt.Dimension(300, 150));
            init(fileName);
        }

        private void init(String fileName) {

            JPanel btnpanel = new JPanel();
            JButton ok = new JButton("ok");
            btnpanel.add(ok);

            JPanel panel = new JPanel();
            panel.add(new OptPanel(fileName));
            panel.add(btnpanel);

            getContentPane().add(panel);

            ok.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                    listener.propertyChange(null);
                }
            });

            pack();
            setVisible(true);
        }
    }

    class OptionsPanel extends InternalFrameChase {
        OptionsPanel(String fileName) {
            super("options", true, true, true, true, new java.awt.Dimension(
                    450, 150));
            init(fileName);
        }

        private void init(String fileName) {

            JPanel btnpanel = new JPanel();
            JButton ok = new JButton("ok");
            btnpanel.add(ok);

            JPanel panel = new JPanel();
            panel.add(new OptPanel(fileName));
            panel.add(btnpanel);

            getContentPane().add(panel);

            ok.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
                    listener.propertyChange(null);
                }
            });
        }
    }

    class OptPanel extends JPanel {
        private String fileName;

        OptPanel(String fileName) {
            this.fileName = fileName;
            init();
        }

        private void init() {
            Nfdynm2AtomCoords parser = new Nfdynm2AtomCoords(fileName);
            int nframe = parser.getNumFrames();
            JPanel pchoice = new JPanel();
            select = new FrameCombo();
            pchoice.add(select);

            tfstart = new JTextField(5);
            tfstart.setText("0");
            tfstart.setEnabled(false);
            JPanel pstart = new JPanel();
            pstart.setBorder(new TitledBorder("start"));
            pstart.add(tfstart);

            tfend = new JTextField(5);
            tfend.setText(String.valueOf(nframe - 1));
            tfend.setEnabled(false);
            JPanel pend = new JPanel();
            pend.setBorder(new TitledBorder("end"));
            pend.add(tfend);

            tfgap = new JTextField(5);
            tfgap.setText("1");
            tfgap.setEnabled(false);
            JPanel pgap = new JPanel();
            pgap.setBorder(new TitledBorder("gap"));
            pgap.add(tfgap);

            select.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    String choi = select.getChoice();
                    boolean enab = false;
                    if (choi.equals(FrameCombo.ALL_FRAME))
                        enab = true;
                    tfstart.setEnabled(enab);
                    tfend.setEnabled(enab);
                    tfgap.setEnabled(enab);
                }
            });

            JPanel pp = new JPanel();
            pp.setLayout(new GridLayout(1, 3));
            pp.add(pstart);
            pp.add(pend);
            pp.add(pgap);

            JPanel panel = new JPanel();

            panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
            panel.add(pchoice);
            panel.add(pp);

            add(panel);
        }
    }
}

class DynmFileFilter extends javax.swing.filechooser.FileFilter {
    public boolean accept(File f) {
        return true;
    }

    public String getDescription() {
        return "F_DYNM file (default name: nfdynm.data)";
    }

}
