/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UpdateItselfDialog.java
 *
 * Created on May 24, 2013, 3:54:59 PM
 */
package org.cobi.kgg.ui.dialog;

import java.awt.Color;
import javax.swing.JOptionPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import org.cobi.kgg.business.entity.Constants;
import org.cobi.kgg.ui.LinkLabel;
import org.openide.util.ImageUtilities;

/**
 *
 * @author mxli
 */
public class UpdateItselfDialog extends javax.swing.JDialog implements Constants {

    /**
     * Creates new form UpdateItselfDialog
     */
    public UpdateItselfDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setIconImage(ImageUtilities.loadImage("org/cobi/kgg/ui/png/16x16/logo1.png"));
       // SwingWorker<List<HttpClient4DownloadTask>, String> swingWorker = new LibCheckerSwingWorker(this);
       // swingWorker.execute();
    }

    /**
     * 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();
        jLabel2 = new LinkLabel ("KGG Website", "http://grass.cgs.hku.hk/limx/kgg/download.php");
        jLabel1 = new javax.swing.JLabel();
        statusLabel = new javax.swing.JLabel();
        exitButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        inforTextPane = new javax.swing.JTextPane();
        downloadProgressBar = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(UpdateItselfDialog.class, "UpdateItselfDialog.title")); // NOI18N

        jLabel2.setText(org.openide.util.NbBundle.getMessage(UpdateItselfDialog.class, "UpdateItselfDialog.jLabel2.text")); // NOI18N

        jLabel1.setText(org.openide.util.NbBundle.getMessage(UpdateItselfDialog.class, "UpdateItselfDialog.jLabel1.text")); // NOI18N

        statusLabel.setText(org.openide.util.NbBundle.getMessage(UpdateItselfDialog.class, "UpdateItselfDialog.statusLabel.text")); // NOI18N

        exitButton.setText(org.openide.util.NbBundle.getMessage(UpdateItselfDialog.class, "UpdateItselfDialog.exitButton.text")); // NOI18N
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(inforTextPane);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(downloadProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 562, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 562, Short.MAX_VALUE)
                    .addComponent(statusLabel)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 205, Short.MAX_VALUE)
                        .addComponent(exitButton)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(downloadProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(exitButton))
                .addGap(16, 16, 16))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

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

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_exitButtonActionPerformed

    /*
    class LibCheckerSwingWorker extends SwingWorker<List<HttpClient4DownloadTask>, String> {

        JDialog parantDialog;
        int MAX_TASK = 1;
        ExecutorService exec = Executors.newFixedThreadPool(MAX_TASK);
        CompletionService<String> serv = new ExecutorCompletionService<String>(exec);
        List<String> updatedURLFiles = new ArrayList<String>();
        int runningThread = 0;

        public LibCheckerSwingWorker(JDialog parantDialog) {
            this.parantDialog = parantDialog;
        }

        @Override
        protected List<HttpClient4DownloadTask> doInBackground() {
            List<HttpClient4DownloadTask> downloadTask = new ArrayList<HttpClient4DownloadTask>();
            try {

                publish("Checking libraries ...");
                for (int i = 0; i < URL_FILE_PATHES.length; i++) {
                    File newLibFile = new File(GlobalManager.LOCAL_COPY_FOLDER + File.separator + URL_FILE_PATHES[i]);
                    if (!newLibFile.exists()) {
                        updatedURLFiles.add(URL_FILE_PATHES[i]);
                    } else {
                        long fileSize = newLibFile.length();
                        String url = URL_FOLDER + URL_FILE_PATHES[i];

                        long netFileLen = HttpClient4API.getContentLength(url, GlobalManager.proxyBean);
                        if (netFileLen < 100) {
                            continue;
                        }
                        if (fileSize != netFileLen) {
                            updatedURLFiles.add(URL_FILE_PATHES[i]);
                        }
                    }
                }

                if (!updatedURLFiles.isEmpty()) {
                    publish("Updating libraries ...");
                    int filesNum = updatedURLFiles.size();

                    for (int i = 0; i < filesNum; i++) {
                        final HttpClient4DownloadTask task = new HttpClient4DownloadTask(KGG_RESOURCE_URL + updatedURLFiles.get(i), 9, GlobalManager.proxyBean);
                        final String fileName = updatedURLFiles.get(i);
                        File newLibFile = new File(GlobalManager.LOCAL_COPY_FOLDER + File.separator + updatedURLFiles.get(i));
                        File libFolder = newLibFile.getParentFile();
                        if (!libFolder.exists()) {
                            libFolder.mkdirs();
                        }
                        task.setLocalPath(newLibFile.getCanonicalPath());
                        task.addTaskListener(new DownloadTaskListener() {
                            @Override
                            public void autoCallback(DownloadTaskEvent event) {
                                int progess = (int) (event.getTotalDownloadedCount() * 100.0 / event.getTotalCount());
                                downloadProgressBar.setValue(progess);
                                statusLabel.setText("Downloading: " + fileName + " RealTimeSpeed: " + event.getRealTimeSpeed() + " GlobalSpeed:" + event.getGlobalSpeed());
                            }

                            @Override
                            public void taskCompleted() throws Exception {
                                statusLabel.setText(fileName + " downloaded!");
                            }
                        });

                        // task.call();
                        //exec.submit(task);
                        serv.submit(task);
                        downloadTask.add(task);
                        runningThread++;
                    }

                    for (int index = 0; index < runningThread; index++) {
                        Future<String> task = serv.take();
                        String download = task.get();
                        publish(download);
                    }
                    exec.shutdown();
                }

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(parantDialog, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
            }
            return downloadTask;
        }

        @Override
        protected void process(List<String> chunks) {
            // TODO Auto-generated method stub  
            for (String message : chunks) {
                insertString2Panel(message);
            }
        }

        @Override
        protected void done() {
            // TODO Auto-generated method stub  
            try {
                //get() : Waits if necessary for the computation to complete, and then retrieves its result.   
                for (HttpClient4DownloadTask task : get()) {
                    insertString2Panel(task.getLocalPath() + " has been updated successfully!");
                }
                Utils.updateLocal(GlobalManager.LOCAL_COPY_FOLDER, GlobalManager.LOCAL_LIB_FOLDER+"/kgg4/modules", updatedURLFiles.toArray(new String[0]));

                insertString2Panel("The whole library has been updated successfully!\n Please re-initiate this application!");

            } catch (Exception e) {
                JOptionPane.showMessageDialog(parantDialog, e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
*/
    public void insertString2Panel(String str) {
        SimpleAttributeSet attrset = new SimpleAttributeSet();
        StyleConstants.setForeground(attrset, Color.BLACK);

        //StyleConstants.setForeground(attrset, Color.BLUE.brighter());
        //StyleConstants.setBold(attrset, true);
        StyleConstants.setFontFamily(attrset, "Courier New");
        StyleConstants.setFontSize(attrset, 13);
        insert(str, attrset);
    }

    private void insert(String str, AttributeSet attrset) {
        Document docs = inforTextPane.getDocument();
        str = str + "\n";
        try {
            docs.insertString(docs.getLength(), str, attrset);
        } catch (BadLocationException ble) {
            JOptionPane.showMessageDialog(this, "BadLocationException:" + ble, "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * @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(UpdateItselfDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UpdateItselfDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UpdateItselfDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UpdateItselfDialog.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() {
                UpdateItselfDialog dialog = new UpdateItselfDialog(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.JProgressBar downloadProgressBar;
    private javax.swing.JButton exitButton;
    private javax.swing.JTextPane inforTextPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel statusLabel;
    // End of variables declaration//GEN-END:variables
}
