/*
 * To change this template, 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.List;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.meteoinfo.map.config.GenericFileFilter;
import org.meteoinfo.image.ImageUtil;

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

    /**
     * Creates new form FrmGifAnimator
     */
    public FrmGifAnimator(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.jList_ImageFiles.setModel(new DefaultListModel());
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList_ImageFiles = new javax.swing.JList();
        jButton_AddFiles = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField_Delay = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField_Repeat = new javax.swing.JTextField();
        jButton_Create = new javax.swing.JButton();
        jButton_Clear = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane1.setViewportView(jList_ImageFiles);

        jButton_AddFiles.setText("Add Image Files");
        jButton_AddFiles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AddFilesActionPerformed(evt);
            }
        });

        jLabel1.setText("Delay (ms):");

        jTextField_Delay.setText("1000");

        jLabel2.setText("Repeat times:");

        jTextField_Repeat.setText("0");

        jButton_Create.setText("Create");
        jButton_Create.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CreateActionPerformed(evt);
            }
        });

        jButton_Clear.setText("Clear");
        jButton_Clear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_ClearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jButton_AddFiles)
                        .addGap(37, 37, 37)
                        .addComponent(jButton_Clear)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField_Delay, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(37, 37, 37)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField_Repeat, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                        .addComponent(jButton_Create, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_AddFiles)
                    .addComponent(jButton_Clear))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField_Delay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField_Repeat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_Create))
                .addContainerGap())
        );

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

    private void jButton_AddFilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AddFilesActionPerformed
        // TODO add your handling code here:
        String path = System.getProperty("user.dir");
        File pathDir = new File(path);

        JFileChooser aDlg = new JFileChooser();
        aDlg.setAcceptAllFileFilterUsed(false);
        aDlg.setCurrentDirectory(pathDir);
        String[] fileExts = new String[]{"gif", "jpg", "png"};
        GenericFileFilter allFileFilter = new GenericFileFilter(fileExts, "Supported Formats");
        aDlg.addChoosableFileFilter(allFileFilter);
        fileExts = new String[]{"gif"};
        GenericFileFilter gifFileFilter = new GenericFileFilter(fileExts, "Gif File (*.gif)");
        aDlg.addChoosableFileFilter(gifFileFilter);
        fileExts = new String[]{"png"};
        GenericFileFilter pngFileFilter = new GenericFileFilter(fileExts, "Png File (*.png)");
        aDlg.addChoosableFileFilter(pngFileFilter);
        fileExts = new String[]{"jpg"};
        GenericFileFilter jpgFileFilter = new GenericFileFilter(fileExts, "Jpeg File (*.jpg)");
        aDlg.addChoosableFileFilter(jpgFileFilter);
        aDlg.setFileFilter(allFileFilter);
        aDlg.setMultiSelectionEnabled(true);
        if (JFileChooser.APPROVE_OPTION == aDlg.showOpenDialog(this)) {
            File[] files = aDlg.getSelectedFiles();
            System.setProperty("user.dir", files[0].getParent());
            DefaultListModel listModel = (DefaultListModel) this.jList_ImageFiles.getModel();
            if (listModel == null) {
                listModel = new DefaultListModel();
            }
            for (File f : files) {
                listModel.addElement(f.getAbsoluteFile());
            }
            this.jList_ImageFiles.setModel(listModel);
        }
    }//GEN-LAST:event_jButton_AddFilesActionPerformed

    private void jButton_ClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ClearActionPerformed
        // TODO add your handling code here:
        this.jList_ImageFiles.setModel(new DefaultListModel());
    }//GEN-LAST:event_jButton_ClearActionPerformed

    private void jButton_CreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CreateActionPerformed
        // TODO add your handling code here:
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        String path = System.getProperty("user.dir");
        File pathDir = new File(path);
        JFileChooser saveDlg = new JFileChooser();
        saveDlg.setAcceptAllFileFilterUsed(false);
        saveDlg.setCurrentDirectory(pathDir);
        String[] fileExts = new String[]{"gif"};
        GenericFileFilter gifFileFilter = new GenericFileFilter(fileExts, "Gif File (*.gif)");
        saveDlg.setFileFilter(gifFileFilter);
        if (JFileChooser.APPROVE_OPTION == saveDlg.showSaveDialog(this)) {
            File outfile = saveDlg.getSelectedFile();
            String extent = ((GenericFileFilter) saveDlg.getFileFilter()).getFileExtent();
            String fileName = outfile.getAbsolutePath();
            if (!fileName.substring(fileName.length() - extent.length()).equals(extent)) {
                fileName = fileName + "." + extent;
            }            

            DefaultListModel listModel = (DefaultListModel) this.jList_ImageFiles.getModel();
            List<String> fns = new ArrayList<String>();
            for (int i = 0; i < listModel.getSize(); i++) {
                fns.add(listModel.get(i).toString());
            }
            int delay = Integer.parseInt(this.jTextField_Delay.getText());
            int repeat = Integer.parseInt(this.jTextField_Repeat.getText());
            ImageUtil.createGifAnimator(fns, fileName, delay, repeat);
            JOptionPane.showMessageDialog(null, "Gif animator file is created!");
        }
        
        this.setCursor(Cursor.getDefaultCursor());
    }//GEN-LAST:event_jButton_CreateActionPerformed

    /**
     * @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(FrmGifAnimator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmGifAnimator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmGifAnimator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmGifAnimator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmGifAnimator dialog = new FrmGifAnimator(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_AddFiles;
    private javax.swing.JButton jButton_Clear;
    private javax.swing.JButton jButton_Create;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList_ImageFiles;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField_Delay;
    private javax.swing.JTextField jTextField_Repeat;
    // End of variables declaration//GEN-END:variables
}
