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

/*
 * CheckUpdatesDialog.java
 *
 * Created on Apr 28, 2009, 3:21:43 PM
 */

package org.statcato;

import org.statcato.utils.HelperFunctions;
import org.statcato.file.ExtensionFileFilter;
import org.statcato.file.DownloadFile;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.io.File;

/**
 * A dialog that checks if a new version is available from the Statcato web
 * site.  A download button is shown if a new version is available.  It allows
 * the user to download the latest version by clicking the download button.
 * 
 * @author Margaret Yau
 * @version %I%, %G%
 * @since 1.0
 */
public class CheckUpdatesDialog extends StatcatoDialog {
    String currentVersion;

    /** Creates new form CheckUpdatesDialog */
    public CheckUpdatesDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.app = (Statcato)parent;
        initComponents();
        setHelpFile("updates");
        name = "Check for Updates";
        DownloadButton.setVisible(false);
        
        // check for new version
        currentVersion = HelperFunctions.getVersionNumberFromWeb();
        thisVersionLabel.setText("This is Statcato version " +
                Statcato.VERSION + ".");
        if (currentVersion.equals("error")) {
            CurrentVersionLabel.setText("Error obtaining the current " +
                    "number from web.  Check network connection.");
        }
        else if (currentVersion.equals(Statcato.VERSION)) {
            // this is the current version
            CurrentVersionLabel.setText("No new updates.");
        }
        else {
            // new version available
            CurrentVersionLabel.setText(
                    "<html>New version " + currentVersion +
                    " is available.<br>" +
                    "  Visit " +
                    "http://www.statcato.org to obtain the latest" +
                    " version.</html>");
            DownloadButton.setVisible(true);
        }

    }

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

        thisVersionLabel = new javax.swing.JLabel();
        ResultPanel = new javax.swing.JPanel();
        CurrentVersionLabel = new javax.swing.JLabel();
        DownloadButton = new javax.swing.JButton();
        OKButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Statcato Updates");

        thisVersionLabel.setText("This is Statcato version");

        ResultPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        CurrentVersionLabel.setText("New version");

        DownloadButton.setText("Download the Latest Version");
        DownloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DownloadButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ResultPanelLayout = new javax.swing.GroupLayout(ResultPanel);
        ResultPanel.setLayout(ResultPanelLayout);
        ResultPanelLayout.setHorizontalGroup(
            ResultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ResultPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ResultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(CurrentVersionLabel)
                    .addComponent(DownloadButton))
                .addContainerGap(79, Short.MAX_VALUE))
        );
        ResultPanelLayout.setVerticalGroup(
            ResultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ResultPanelLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(CurrentVersionLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addComponent(DownloadButton)
                .addContainerGap())
        );

        OKButton.setText("OK");
        OKButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OKButtonActionPerformed(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()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(OKButton)
                    .addComponent(ResultPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(thisVersionLabel))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addComponent(thisVersionLabel)
                .addGap(18, 18, 18)
                .addComponent(ResultPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addComponent(OKButton)
                .addGap(23, 23, 23))
        );

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

    private void DownloadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DownloadButtonActionPerformed
        // download latest version from web
        String fileName = "statcato_" + currentVersion + ".zip";

            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File(fileName));
            ExtensionFileFilter ZipFilter = new ExtensionFileFilter("Zip (*.zip)", "zip");
            fc.addChoosableFileFilter(ZipFilter);
            fc.setAcceptAllFileFilterUsed(false);

            int returnValue = fc.showSaveDialog(this);

            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                String path = file.getPath();

                if (file.exists()) { // file exists already
                    Object[] options = {"Overwrite file", "Cancel"};
                    int choice = JOptionPane.showOptionDialog(this,
                            "The specified file already exists.  Overwrite existing file?",
                            "Overwrite file?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
                            null, options, options[1]);
                    if (choice != 0)   // don't overwrite
                        return;
                }
                // download file
                DownloadFile d = new DownloadFile(
                    "http://www.statcato.org/versions/statcato_" + currentVersion +
                    ".zip");
                int totalDownload = d.download(path);
                if (totalDownload <= 0) {
                    JOptionPane.showMessageDialog(this,
                            "Download failed.", "Download error",
                            JOptionPane.ERROR_MESSAGE);
                }
                else {
                    JOptionPane.showMessageDialog(this,
                            "The latest version is downloaded to " +
                            path,
                            "Download complete",
                            JOptionPane.PLAIN_MESSAGE);
                }
            }
    }//GEN-LAST:event_DownloadButtonActionPerformed

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OKButtonActionPerformed
        dispose();
    }//GEN-LAST:event_OKButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel CurrentVersionLabel;
    private javax.swing.JButton DownloadButton;
    private javax.swing.JButton OKButton;
    private javax.swing.JPanel ResultPanel;
    private javax.swing.JLabel thisVersionLabel;
    // End of variables declaration//GEN-END:variables

}
