/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/03/09, 18:30
!  AUTHOR(S): KOGA, Junichiro
!  File : PPViewer.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;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionListener;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ElementInfo;
import ciss.phase_viewer.common.Utils;
import ciss.phase_viewer.projectbrowser.ProjectInfo;
import ciss.phase_viewer.projectbrowser.ProjectManipulator;
import ciss.phase_viewer.projectbrowser.tools.NoFilePanel;

/**
 * 擬ポテンシャルを見るGUI. 便宜上「ProjectManipulator」としているけど特にプロジェクト情報などは不要.
 * 
 * @author
 */
public class PPViewer extends ProjectManipulator implements
        ListSelectionListener {
    private Logger logger = Logger.getLogger(PPViewer.class.getName());
    private String ppdir = Utils.getDefaultPPDir();
    private File ppprops = new File(ppdir
            + System.getProperty("file.separator") + "pseudopotspec.data");

    public PPViewer(ProjectInfo projectInfo) {
        super(projectInfo);
    }

    public void initializeProject() {
    }

    public void init() {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        createPPProps();
        if (dat == null) {
            add(new NoFilePanel("F_POT"));
            return;
        }
        JPanel plist = new JPanel();
        plist.setBorder(new TitledBorder("pp filename"));
        plist.setLayout(new BoxLayout(plist, BoxLayout.Y_AXIS));
        String[] fname = new String[dat.length];
        for (int i = 0; i < fname.length; i++) {
            fname[i] = dat[i].fileName;
        }
        list = new JList(fname);
        JScrollPane pane = new JScrollPane(list);
        plist.add(pane);
        add(plist);
        panelProps = new JPanel();
        panelProps.setBorder(new TitledBorder("properties"));
        label = new JLabel("");
        panelProps.add(label);
        add(panelProps);
        JButton btn = new JButton("close");
        JPanel p = new JPanel();
        p.add(btn);
        add(p);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                projectInfo.getParent().dispose();
            }
        });

        list.addListSelectionListener(this);
        list.setSelectedIndex(0);
    }

    private PPData[] dat;

    private void createPPProps() {
        File[] files = new File(ppdir).listFiles();
        Vector pps = new Vector();
        if (files == null || files.length == 0) {
            logger.error("ppdir is empty!");
            return;
        }
        ElementInfo info = ElementInfo.getElementInfo();
        for (int i = 0; i < files.length; i++) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(files[i]));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (!line.startsWith("#")) {
                        break;
                    }
                }
                String[] array = line.split("\\s+");
                if (array == null || array.length < 5) {
                    continue;
                }
                String fname = files[i].getName();
                int atomicNumber = -1;
                int ppc = -1;
                int val = -1;
                try {
                    atomicNumber = Integer.parseInt(array[0]);
                    ppc = Integer.parseInt(array[3]);
                    val = Integer.parseInt(array[1]);
                } catch (Exception exc) {
                    continue;
                }
                if (atomicNumber < 0 || ppc < 0) {
                    continue;
                }
                String elemName = info.getSymbolFromNumber(atomicNumber);
                String[] foo = fname.split("_");
                if (elemName == null || elemName.trim().length() == 0) {
                    if (foo != null && foo.length != 0) {
                        elemName = foo[0];
                    }
                }
                String type = "";
                if (foo != null && foo.length >= 3) {
                    type = foo[2];
                }
                String xctype = reader.readLine().trim().split("\\s+")[0];

                PPData data = new PPData(fname, elemName, atomicNumber, val,
                        type, xctype, ppc);
                pps.addElement(data);
            } catch (Exception exc) {
                exc.printStackTrace();
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (Exception exc) {
                }
            }
        }

        dat = new PPData[pps.size()];
        pps.copyInto(dat);
        Arrays.sort(dat);
    }

    private JPanel panelProps;
    private JList list;
    private JLabel label;

    public void valueChanged(javax.swing.event.ListSelectionEvent e) {

        int i = list.getSelectedIndex();
        PPData da = dat[i];
        String ppc = "on";
        if (da.ppc != 1) {
            ppc = "off";
        }
        String newText = "element: " + da.elementName + " atomic number: "
                + String.valueOf(da.atomicNumber)
                + " number of valence electrons: " + String.valueOf(da.valence)
                + " ppc: " + ppc + " xctype: " + da.xctype + " type: "
                + da.type;
        label.setText(newText);
        revalidate();
    }

    class PPData implements Comparable {
        String fileName;
        String elementName;
        int atomicNumber;
        int valence;
        String xctype;
        String type;
        int ppc;

        PPData(String fileName, String elementName, int atomicNumber,
                int valence, String type, String xctype, int ppc) {
            this.fileName = fileName;
            this.elementName = elementName;
            this.atomicNumber = atomicNumber;
            this.valence = valence;
            this.type = type;
            this.xctype = xctype;
            this.ppc = ppc;
        }

        PPData(String longString) {
            String[] array = longString.split(",");
            try {
                this.fileName = array[0].split("=")[1];
                this.atomicNumber = Integer.parseInt(array[1].split("=")[1]);
                this.valence = Integer.parseInt(array[2].split("=")[1]);
                this.elementName = array[3].split("=")[1];
                this.type = array[4].split("=")[1];
                this.xctype = array[5].split("=")[1];
                String foo = array[6].split("=")[1];
                if (foo.equals("on")) {
                    this.ppc = 1;
                } else {
                    this.ppc = 0;
                }
            } catch (Exception exc) {
                // exc.printStackTrace();
            }
        }

        public int compareTo(Object o) {
            PPData from = (PPData) o;
            if (from.atomicNumber != atomicNumber) {
                return atomicNumber - from.atomicNumber;
            }
            return fileName.compareTo(from.fileName);
        }

        public String toString() {
            String ret = "fileName=" + fileName;
            ret += ",atomicNumber=" + String.valueOf(atomicNumber);
            ret += ",valence=" + String.valueOf(valence);
            ret += ",element=" + elementName;
            ret += ",type=" + type;
            ret += ",xctype=" + xctype;

            if (ppc == 1) {
                ret += ",ppc=on";
            } else {
                ret += ",ppc=off";
            }
            return ret;
        }
    }
}
