/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.meteoinfo.map.forms;

import java.awt.Cursor;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.meteoinfo.data.meteodata.netcdf.NetCDFDataInfo;
import org.meteoinfo.map.config.GenericFileFilter;

/**
 *
 * @author yaqiang
 */
public class FrmJoinNCFiles extends javax.swing.JDialog {

    /**
     * Creates new form FrmJoinNCFiles
     * @param parent
     * @param modal
     */
    public FrmJoinNCFiles(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        this.jList_AllFiles.setModel(new DefaultListModel());
        this.jList_SelectedFiles.setModel(new DefaultListModel());
        File path = new File(System.getProperty("user.dir"));
        this.setDataFolder(path);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton_DataFolder = new javax.swing.JButton();
        jLabel_DataFolder = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList_AllFiles = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList_SelectedFiles = new javax.swing.JList();
        jButton_SelectAll = new javax.swing.JButton();
        jButton_UnSelecte = new javax.swing.JButton();
        jButton_Select = new javax.swing.JButton();
        jButton_UnSelectAll = new javax.swing.JButton();
        jButton_Join = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField_TimeDimName = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jButton_DataFolder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Folder_1_16x16x8.png"))); // NOI18N
        jButton_DataFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_DataFolderActionPerformed(evt);
            }
        });

        jLabel_DataFolder.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jList_AllFiles.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList_AllFiles);

        jList_SelectedFiles.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jList_SelectedFiles);

        jButton_SelectAll.setFont(new java.awt.Font("宋体", 1, 15)); // NOI18N
        jButton_SelectAll.setText(">>");
        jButton_SelectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_SelectAllActionPerformed(evt);
            }
        });

        jButton_UnSelecte.setFont(new java.awt.Font("宋体", 1, 15)); // NOI18N
        jButton_UnSelecte.setText("<");
        jButton_UnSelecte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_UnSelecteActionPerformed(evt);
            }
        });

        jButton_Select.setFont(new java.awt.Font("宋体", 1, 15)); // NOI18N
        jButton_Select.setText(">");
        jButton_Select.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_SelectActionPerformed(evt);
            }
        });

        jButton_UnSelectAll.setFont(new java.awt.Font("宋体", 1, 15)); // NOI18N
        jButton_UnSelectAll.setText("<<");
        jButton_UnSelectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_UnSelectAllActionPerformed(evt);
            }
        });

        jButton_Join.setText("Join");
        jButton_Join.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_JoinActionPerformed(evt);
            }
        });

        jLabel1.setText("Time Dimension Name:");

        jTextField_TimeDimName.setText("time");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton_Select, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton_UnSelecte, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton_SelectAll, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton_UnSelectAll, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton_DataFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel_DataFolder, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField_TimeDimName, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addComponent(jButton_Join, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 58, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton_DataFolder, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel_DataFolder, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(70, 70, 70)
                        .addComponent(jButton_Select)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton_UnSelecte)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton_SelectAll)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton_UnSelectAll))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                            .addComponent(jScrollPane1))))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Join)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField_TimeDimName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_DataFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_DataFolderActionPerformed
        // TODO add your handling code here:
        JFileChooser aDlg = new JFileChooser();
        String path = System.getProperty("user.dir");
        File pathDir = new File(path);
        if (pathDir.isDirectory()) {
            aDlg.setCurrentDirectory(pathDir);
        }
        aDlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (JFileChooser.APPROVE_OPTION == aDlg.showOpenDialog(this)) {
            File aFile = aDlg.getSelectedFile();
            System.setProperty("user.dir", aFile.getAbsolutePath());
            
            this.setDataFolder(aFile);
        }
    }//GEN-LAST:event_jButton_DataFolderActionPerformed

    private void jButton_SelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SelectActionPerformed
        // TODO add your handling code here:
        DefaultListModel listModel_sel = (DefaultListModel)this.jList_SelectedFiles.getModel();
        List<String> selNames = this.jList_AllFiles.getSelectedValuesList();
        for (String name : selNames){
            listModel_sel.addElement(name);
        }
    }//GEN-LAST:event_jButton_SelectActionPerformed

    private void jButton_UnSelecteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_UnSelecteActionPerformed
        // TODO add your handling code here:
        DefaultListModel listModel_sel = (DefaultListModel)this.jList_SelectedFiles.getModel();
        List<String> selNames = this.jList_SelectedFiles.getSelectedValuesList();
        for (String name : selNames){
            listModel_sel.removeElement(name);
        }
    }//GEN-LAST:event_jButton_UnSelecteActionPerformed

    private void jButton_SelectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SelectAllActionPerformed
        // TODO add your handling code here:
        DefaultListModel listModel_all = (DefaultListModel)this.jList_AllFiles.getModel();
        DefaultListModel listModel_sel = (DefaultListModel)this.jList_SelectedFiles.getModel();
        listModel_sel.clear();
        for (int i = 0; i < listModel_all.getSize(); i++){
            listModel_sel.addElement(listModel_all.getElementAt(i));
        }
    }//GEN-LAST:event_jButton_SelectAllActionPerformed

    private void jButton_UnSelectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_UnSelectAllActionPerformed
        // TODO add your handling code here:
        DefaultListModel listModel_sel = (DefaultListModel)this.jList_SelectedFiles.getModel();
        listModel_sel.clear();
    }//GEN-LAST:event_jButton_UnSelectAllActionPerformed

    private void jButton_JoinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_JoinActionPerformed
        // TODO add your handling code here:
        DefaultListModel listModel_sel = (DefaultListModel)this.jList_SelectedFiles.getModel();
        List<String> sfns = new ArrayList<>();
        for (int i = 0; i < listModel_sel.getSize(); i++){
            sfns.add(listModel_sel.getElementAt(i).toString());
        }
        if (sfns.size() < 2){
            JOptionPane.showMessageDialog(null, "At least two files should be selected for joining!", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        String path = this.jLabel_DataFolder.getText();
        List<String> fns = new ArrayList<>();
        for (String sfn : sfns){
            String fn = path + File.separator + sfn;
            if (new File(fn).isFile())
                fns.add(fn);
        }
        
        File pathDir = new File(path);
        JFileChooser aDlg = new JFileChooser();
        aDlg.setCurrentDirectory(pathDir);
        String[] fileExts = new String[]{"nc"};
        GenericFileFilter ncFileFilter = new GenericFileFilter(fileExts, "NetCDF file (*.nc)");
        aDlg.setFileFilter(ncFileFilter);        
        aDlg.setAcceptAllFileFilterUsed(false);
        if (JFileChooser.APPROVE_OPTION == aDlg.showSaveDialog(this)) {
            File aFile = aDlg.getSelectedFile();
            System.setProperty("user.dir", aFile.getParent());
            String extent = ((GenericFileFilter) aDlg.getFileFilter()).getFileExtent();
            String fileName = aFile.getAbsolutePath();
            if (!fileName.substring(fileName.length() - extent.length()).equals(extent)) {
                fileName = fileName + "." + extent;
            }
            
            this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            String tDimName = this.jTextField_TimeDimName.getText();
            NetCDFDataInfo.joinDataFiles(fns, fileName, tDimName);
            this.setCursor(Cursor.getDefaultCursor());
        }                
    }//GEN-LAST:event_jButton_JoinActionPerformed

    private void setDataFolder(File path) {
        if (!path.isDirectory())
            return;
        
        this.jLabel_DataFolder.setText(path.getAbsolutePath());
        DefaultListModel listModel_all = (DefaultListModel)this.jList_AllFiles.getModel();
        DefaultListModel listModel_sel = (DefaultListModel)this.jList_SelectedFiles.getModel();
        listModel_all.clear();
        listModel_sel.clear();
        File[] files = path.listFiles();
        Arrays.sort(files);
        for (File file : files) {
            if (file.isFile()) {
                String name = file.getName();
                listModel_all.addElement(name);
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmJoinNCFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmJoinNCFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmJoinNCFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmJoinNCFiles.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                FrmJoinNCFiles dialog = new FrmJoinNCFiles(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_DataFolder;
    private javax.swing.JButton jButton_Join;
    private javax.swing.JButton jButton_Select;
    private javax.swing.JButton jButton_SelectAll;
    private javax.swing.JButton jButton_UnSelectAll;
    private javax.swing.JButton jButton_UnSelecte;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel_DataFolder;
    private javax.swing.JList jList_AllFiles;
    private javax.swing.JList jList_SelectedFiles;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField_TimeDimName;
    // End of variables declaration//GEN-END:variables
}
