/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.meteoinfo.map.forms;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;

import org.meteoinfo.common.util.GlobalUtil;
import org.meteoinfo.map.config.Plugin;
import org.meteoinfo.map.config.PluginCollection;
import org.meteoinfo.ui.CheckBoxListEntry;

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

    private final FrmMain _parent;
    PluginCollection _plugins = new PluginCollection();

    /**
     * Creates new form FrmPluginManager
     * @param parent
     * @param modal
     */
    public FrmPluginManager(JFrame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        _parent = (FrmMain) parent;
        initialize();
    }

    private void initialize() {
        this._plugins = _parent.getPlugins();
        this.updatePluginCheckList();
    }

    private void updatePluginCheckList() {
        DefaultListModel listModel = new DefaultListModel();
        for (Plugin plugin : _plugins) {
            listModel.addElement(new CheckBoxListEntry(plugin, plugin.isLoad()));
        }
        this.checkBoxList_Plugin.setModel(listModel);
    }

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

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        checkBoxList_Plugin = new org.meteoinfo.ui.JCheckBoxList();
        jButton_UpdateList = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea_PluginDetails = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Plugin Manager");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Plugins"));

        checkBoxList_Plugin.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]; }
        });
        checkBoxList_Plugin.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkBoxList_PluginMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(checkBoxList_Plugin);

        jButton_UpdateList.setText("Update List");
        jButton_UpdateList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_UpdateListActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 391, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(126, 126, 126)
                        .addComponent(jButton_UpdateList)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_UpdateList))
        );

        jLabel1.setText("Plugin:");

        jTextArea_PluginDetails.setColumns(20);
        jTextArea_PluginDetails.setRows(5);
        jScrollPane2.setViewportView(jTextArea_PluginDetails);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                .addContainerGap())
        );

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

    private void checkBoxList_PluginMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBoxList_PluginMouseClicked
        // TODO add your handling code here:
        DefaultListModel listModel = (DefaultListModel) this.checkBoxList_Plugin.getModel();
        int idx = this.checkBoxList_Plugin.getSelectedIndex();
        CheckBoxListEntry item = (CheckBoxListEntry) listModel.getElementAt(idx);
        Plugin plugin = (Plugin) item.getValue();
        if (item.isSelected()) {
            if (!plugin.isLoad()) {
                _parent.loadPlugin(plugin);
                _parent.validate();
            }
        } else {
            if (plugin.isLoad()) {
                _parent.unloadPlugin(plugin);
                _parent.validate();
            }
        }

        String detailStr = "Name: " + plugin.getName()
                + System.getProperty("line.separator") + "Author: " + plugin.getAuthor()
                + System.getProperty("line.separator") + "Version: " + plugin.getVersion()
                + System.getProperty("line.separator") + "Description: " + plugin.getDescription()
                + System.getProperty("line.separator") + "Jar Path: " + plugin.getJarPath()
                + System.getProperty("line.separator") + "Class Name: " + plugin.getClassName();
        this.jTextArea_PluginDetails.setText(detailStr);
    }//GEN-LAST:event_checkBoxList_PluginMouseClicked

    private void jButton_UpdateListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_UpdateListActionPerformed
        // TODO add your handling code here:
        List<Plugin> plugins = new ArrayList<>();

        String pluginPath = _parent.getPlugins().getPluginPath();
        if (new File(pluginPath).isDirectory()) {
            List<String> fileNames = GlobalUtil.getFiles(pluginPath, ".jar");
            for (String fn : fileNames) {
                Plugin plugin = _parent.readPlugin(fn);
                if (plugin != null) {
                    plugins.add(plugin);
                }
            }

            List<String> pluginNames = new ArrayList<>();
            for (Plugin plugin : _plugins) {
                pluginNames.add(plugin.getName());
            }

            List<String> newPluginNames = new ArrayList<>();
            for (Plugin plugin : plugins) {
                newPluginNames.add(plugin.getName());
            }

            for (int i = 0; i < _plugins.size(); i++) {
                if (!newPluginNames.contains(_plugins.get(i).getName())) {
                    _parent.removePlugin(_plugins.get(i));
                    _plugins.remove(i);
                    i -= 1;
                }
            }

            for (Plugin plugin : plugins) {
                if (!pluginNames.contains(plugin.getName())) {
                    _plugins.add(plugin);
                    try {
                        _parent.addPlugin(plugin);
                    } catch (IOException ex) {
                        Logger.getLogger(FrmPluginManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }

            this.updatePluginCheckList();
        }
    }//GEN-LAST:event_jButton_UpdateListActionPerformed

    /**
     * @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(FrmPluginManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmPluginManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmPluginManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmPluginManager.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() {
                FrmPluginManager dialog = new FrmPluginManager(new FrmMain(), 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 org.meteoinfo.ui.JCheckBoxList checkBoxList_Plugin;
    private javax.swing.JButton jButton_UpdateList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea_PluginDetails;
    // End of variables declaration//GEN-END:variables
}
