/*
 * LoadDatasetDialog.java
 *
 * Created on June 19, 2008, 11:09 AM
 */

package org.statcato.dialogs.file;

import org.statcato.file.FileChooserUtils;
import org.statcato.file.DownloadFile;
import org.statcato.*;
import org.statcato.utils.*;
import java.io.*;
import java.util.*;
import javax.swing.ButtonGroup;

/**
 * A dialog that allows the user to load a built-in dataset or 
 * a dataset from a web address into the Datasheet pane.
 * 
 * @author  Margaret Yau
 * @version %I%, %G%
 * @since 1.0
 */
public class LoadDatasetDialog extends StatcatoDialog {    
    // file type constants
    private static int EXCEL = 0;
    private static int CSV = 1;
    private static int TXT = 2;
    private static String[] extensions = {"xls", "csv", "txt"};
    
    // sample datasets titles & corresponding filenames
    private static String titles[] = {
        "",
        "Beam Deflections",
        "Caffeine Consumption at Starbucks vs. Time of Day",
        "Cuckoo Eggs & Foster Parents",
        "Eye Gain Ratio Measurements for Schizophrenic Patients",
        "GPA vs. Environmental Concern",
        "Homework Scores vs. Overall Course Percentages for Statistics Students",
        "Lifetimes of Aluminum Strips Under Alternating Stress",
        "Machine # vs. Part Diameter",
        "Mass vs. Spring Frequency",
        "Pain Reliever vs. Body Temperature",
        "Pendulum Length vs. Period",
        "Precipitation vs. Lake Level",
        "Rainfall Totals for Seeded and Unseeded Clouds",
        "Sample Size vs. Error",
        "Smoking vs. GPA",
        "Time vs. H1N1 Cases",
        "Time vs. Ibuprofen Qty.",
        "Time vs. Success Rate",
        "Tips vs. Gender",
        "Women in Math Courses",
    };
    static String paths[] = {
        "",
        "BeamDeflections.xls",
        "CaffeineConsumptionVsTime.xls",
        "CuckooEggVsFosterParents.xls",
        "SchizEye.xls",
        "GPAVsEnvConcern.xls",
        "HWvsOverall.xls",
        "AlumLife.xls",
        "MachineVsPartDiameter.xls",
        "MassVsSpringFreq.xls",
        "PainRelieverVsBodyTemp.xls",
        "PendulumLengthVsTime.xls",
        "PrecipitationVsLakeLevel.xls",
        "Rainfall.xls",
        "SampleSizeVsError.xls",
        "SmokingVsGPA.xls",
        "TimeVsH1N1.xls",
        "TimeVsIbuprofen.xls",
        "TimeVsSuccessRate.xls",
        "TipsVsGender.xls",
        "WomenInMath.xls"
    };
        
    /** Creates new form LoadDatasetDialog */
    public LoadDatasetDialog(java.awt.Frame parent, boolean modal, Statcato app) {
        super(parent, modal);
        this.app = app;
        ParentSpreadsheet = app.getSpreadsheet();
        
        initComponents();
                
        ButtonGroup group = new ButtonGroup();
        group.add(SampleRadioButton);
        group.add(WebRadioButton);
        
        // load items into built-in datasets combo box
        loadSampleComboBox();
        
        getRootPane().setDefaultButton(OKButton);
        setHelpFile("file-menu");
        name = "Load Dataset";
        description = "For loading a built-in dataset or a dataset available on the web.";
        helpStrings.add("Select a built-in sample dataset or enter " +
                "the url of a dataset available on the web.");
    }
    
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        SampleComboBox = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        URLTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        TypeComboBox = new javax.swing.JComboBox();
        OKButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        SampleRadioButton = new javax.swing.JRadioButton();
        WebRadioButton = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Load Dataset");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setText("Built-in Datasets");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel2.setText("Online Datasets");

        URLTextField.setEnabled(false);

        jLabel5.setText("Select dataset file type:");

        TypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Excel (.xls)", "Comma-separated values (.csv)", "Tab-delimited text (.txt)" }));
        TypeComboBox.setEnabled(false);

        OKButton.setText("Load Dataset");
        OKButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OKButtonActionPerformed(evt);
            }
        });

        CancelButton.setText("Cancel");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        SampleRadioButton.setSelected(true);
        SampleRadioButton.setText("Choose a sample dataset:");
        SampleRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                SampleRadioButtonStateChanged(evt);
            }
        });

        WebRadioButton.setText("Enter web address of the dataset (e.g. http://www.statcato.org/labs/data/ages.csv):");
        WebRadioButton.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                WebRadioButtonStateChanged(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()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(WebRadioButton)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(21, 21, 21)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(TypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(SampleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(URLTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(189, 189, 189)
                        .addComponent(OKButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(SampleRadioButton)))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {CancelButton, OKButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(SampleRadioButton)
                .addGap(7, 7, 7)
                .addComponent(SampleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(WebRadioButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(URLTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(TypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OKButton)
                    .addComponent(CancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

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

        int index = SampleComboBox.getSelectedIndex();
        File currentDir = new File(".");
        String currentDirStr = "";
        String fileType;
        try {
            currentDirStr = currentDir.getCanonicalPath();
            File file = null;
            // load sample dataset
            if (SampleRadioButton.isSelected()) {
                if (index == 0) {
                    app.showErrorDialog("Select a built-in sample dataset");
                    return;
                }
                else {                   
                    String path = "dataset/" + paths[index];
                    java.net.URL URL = getClass().getResource(path);
                    fileType = FileChooserUtils.getExtension(URL.toString());
                    if (URL == null) {
                        app.showErrorDialog("Cannot read file");
                        return;                    
                    }
                    DownloadFile d = new DownloadFile(URL.toString());
                    String filename = d.download();
                    if (filename == null) {
                        app.showErrorDialog("Error downloading file!" +
                                " Please check URL.");
                        return;
                    }
                    file = new File(filename);
                }
            }
            else {  // load dataset from web address
                String URL = URLTextField.getText();
                if (URL.equals("")) {
                    app.showErrorDialog("Enter the web address " +
                            "of the dataset.");
                    return;
                }
                else {
                    int type = TypeComboBox.getSelectedIndex();
                    if (FileChooserUtils.getExtension(URL).equals(extensions[type])) {
                        DownloadFile d = new DownloadFile(URL);
                        String filename = d.download();
                        if (filename == null) {
                            app.showErrorDialog("Error downloading file!" +
                                    " Please check URL.");
                            return;
                        }
                        file = new File(filename);
                    }
                    else {
                        app.showErrorDialog("URL is not compatible with the expected " +
                            "file type.");
                        return;
                    }
                    fileType = extensions[type];
                }
            }
            
            // read data from file
            if (fileType.equals("xls")) {
                Vector<String> sheets = HelperFunctions.readExcelFile(file);
                if (sheets != null) {
                    for (Enumeration e = sheets.elements(); e.hasMoreElements(); ) {
                        String str = (String) e.nextElement();
                        if (!str.trim().equals("")) {
                            app.getDatasheetTabbedPane().addDatasheet(str, null);
                        }
                        
                    }
                }
                else {
                    app.showErrorDialog("Error reading " +
                            "excel file.");
                    return;
                }
            }
            else {
                String contents = HelperFunctions.getFileContents(file);
                if (fileType.equals("csv")) {
                    contents = HelperFunctions.parseCSV(contents);
                }
                app.getDatasheetTabbedPane().addDatasheet(contents, null);
            }
            // remove temporary downloaded file
            boolean success = file.delete();
            if (!success)
                System.out.println("cannot delete temp file");
        }
        catch (IOException e) {
            app.showErrorDialog("Cannot access current directory");
            return;
        }
        
        setVisible(false);
    }//GEN-LAST:event_OKButtonActionPerformed

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_CancelButtonActionPerformed

    private void SampleRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_SampleRadioButtonStateChanged
        if (SampleRadioButton.isSelected()) {
            SampleComboBox.setEnabled(true);
        }
        else {
            SampleComboBox.setEnabled(false);
        }
    }//GEN-LAST:event_SampleRadioButtonStateChanged

    private void WebRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_WebRadioButtonStateChanged
        if (WebRadioButton.isSelected()) {
            URLTextField.setEnabled(true);
            TypeComboBox.setEnabled(true);
        }
        else {
            URLTextField.setEnabled(false);
            TypeComboBox.setEnabled(false);
        }
    }//GEN-LAST:event_WebRadioButtonStateChanged
    
    private void loadSampleComboBox() {
        // clear combo box
        SampleComboBox.removeAllItems();
        
        // add default empty item
        SampleComboBox.addItem("");
        SampleComboBox.setSelectedItem("");

        for (int i = 1; i < titles.length; ++i) 
            SampleComboBox.addItem(titles[i]);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JButton OKButton;
    private javax.swing.JComboBox SampleComboBox;
    private javax.swing.JRadioButton SampleRadioButton;
    private javax.swing.JComboBox TypeComboBox;
    private javax.swing.JTextField URLTextField;
    private javax.swing.JRadioButton WebRadioButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables
    
}
