/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/11/30, 15:33
!  AUTHOR(S): KOGA, Junichiro
!  File : DataSetExporter.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.graph.dataset;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ChaseFileChooser;
import ciss.phase_viewer.mainpanel.InternalFrameChase;

/**
 * DataSetを外部ファイルにエクスポート.
 * 
 * @author
 */
public class DataSetExporter extends InternalFrameChase {
    private Logger logger = Logger.getLogger(DataSetExporter.class.getName());

    private DataSet[] dset;
    private DataSetExporterSubPanel[] subPanels;
    private String dir;
    private JInternalFrame me;

    /** Creates a new instance of DataSetExporter */
    public DataSetExporter(DataSet[] dset) {
        super("export dataset", true, true, true, true, new Dimension(600, 380));
        this.dset = dset;
        this.me = this;
        init();
    }

    private void init() {
        getContentPane().setLayout(new BorderLayout());
        JScrollPane scr = new JScrollPane();
        JPanel p = new JPanel();
        p.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = 0;
        gc.gridy = 0;
        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.weighty = 0;
        gc.weightx = 1;
        subPanels = new DataSetExporterSubPanel[dset.length];
        for (int i = 0; i < dset.length; i++) {
            subPanels[i] = new DataSetExporterSubPanel(dset[i]);
            gc.gridy = i;
            p.add(subPanels[i], gc);
        }
        scr.setPreferredSize(new Dimension(300, 300));
        scr.getViewport().setView(p);
        getContentPane().add(scr, BorderLayout.NORTH);
        getContentPane().add(createBtnPanel(), BorderLayout.SOUTH);
    }

    private JPanel createBtnPanel() {
        JPanel p = new JPanel();
        JButton btndo = new JButton("do export");
        JButton btnclose = new JButton("close");
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.add(btndo);
        p.add(btnclose);

        btndo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for (int i = 0; i < subPanels.length; i++) {
                    subPanels[i].doExport();
                }
            }
        });

        btnclose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        JPanel ret = new JPanel();
        ret.add(p);
        return ret;
    }

    class DataSetExporterSubPanel extends JPanel {
        private DataSet dataSet;
        private JTextField tffilename;
        private JCheckBox checkBox;
        int nameLength = 12;

        DataSetExporterSubPanel(DataSet dataSet) {
            this.dataSet = dataSet;
            setLayout(new GridBagLayout());
            init();
        }

        void doExport() {
            if (!checkBox.isSelected()) {
                logger.debug("check box not selected! export not executed.");
                return;
            }
            File writeTo = new File(tffilename.getText());
            FileWriter writer = null;
            PrintWriter pwriter = null;
            try {
                writer = new FileWriter(writeTo);
                pwriter = new PrintWriter(writer);
                DataSetElement[] dse = dataSet.getData();
                if (dse == null || dse.length == 0) {
                    return;
                }
                String[] idents = new String[dse.length];
                pwriter.print("#");
                for (int i = 0; i < idents.length; i++) {
                    pwriter.print(" " + dse[i].getName());
                }
                pwriter.println("");
                int numData = dse[0].getData().length;
                for (int i = 0; i < numData; i++) {
                    for (int j = 0; j < idents.length; j++) {
                        String[] ar = dse[j].getData();
                        if (ar == null || ar.length == 0) {
                            continue;
                        }
                        pwriter.print(ar[i] + " ");
                    }
                    pwriter.println("");
                }
            } catch (IOException ioe) {
                logger.error("error encountered while exporting data set "
                        + dataSet.getName() + " to "
                        + writeTo.getAbsolutePath());
            } finally {
                try {
                    writer.close();
                    pwriter.close();
                } catch (IOException ioe) {
                }
            }
        }

        private void init() {
            GridBagConstraints gc = new GridBagConstraints();
            gc.gridx = 0;
            gc.gridy = 0;
            gc.weighty = 0;
            gc.weightx = 0;
            JPanel pdsetname = new JPanel();
            String name = dataSet.getName();
            if (name.length() < nameLength) {
                for (int i = name.length(); i < nameLength; i++) {
                    name += " ";
                }
            } else if (name.length() >= nameLength) {
                name = name.substring(0, nameLength - 1);
            }
            JLabel labeldset = new JLabel("dataset: " + name);
            labeldset.setFont(new Font("Monospaced", Font.PLAIN, 12));
            labeldset.setToolTipText(dataSet.getName());
            pdsetname.add(labeldset);
            add(pdsetname, gc);

            JPanel pfilename = new JPanel();
            pfilename.setLayout(new BorderLayout());
            pfilename.setBorder(new TitledBorder("enter filename"));
            tffilename = new JTextField(30);
            File origFile = new File(
                    new File(dataSet.getFileName()).getParent()
                            + System.getProperty("file.separator")
                            + dataSet.getName() + ".data");
            File newFile = origFile;
            int count = 1;
            while (true) {
                if (newFile.exists()) {
                    newFile = new File(origFile.getAbsolutePath()
                            + String.valueOf(count));
                } else {
                    break;
                }
                count++;
            }
            tffilename.setText(newFile.getAbsolutePath());
            pfilename.add(tffilename, BorderLayout.WEST);
            JButton btn = new JButton("choose");
            pfilename.add(btn, BorderLayout.CENTER);
            gc.gridx = 1;
            add(pfilename, gc);

            JPanel pmanip = new JPanel();
            checkBox = new JCheckBox("export this data set");
            pmanip.add(checkBox);
            gc.gridx = 2;
            add(pmanip, gc);

            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ChaseFileChooser fdlg = new ChaseFileChooser();
                    fdlg.setDialogType(JFileChooser.CUSTOM_DIALOG);
                    fdlg.setDialogTitle("select");
                    fdlg.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    if (fdlg.showDialog(me, "open") != JFileChooser.APPROVE_OPTION) {
                        return;
                    }
                    String path = fdlg.getSelectedFile().getAbsolutePath();
                    tffilename.setText(path);
                }
            });

        }

    }
}
