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

package org.javaone.scrambler;

import java.io.File;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JFileChooser;
import org.javaone.anagram.lib.WordLibrary;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.NbPreferences;

/**
 * Top component which displays something.
 */
public final class AnalyzeTextTopComponent extends TopComponent {

    private File textFile;
    private Scrambler scrambler;

    private static AnalyzeTextTopComponent instance;

    private static final String PREFERRED_ID = "AnalyzeTextTopComponent";

    private final Preferences pref = NbPreferences.forModule(ScramblerComplexityPanel.class);

    public AnalyzeTextTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(AnalyzeTextTopComponent.class, "CTL_AnalyzeTextTopComponent"));
        setToolTipText(NbBundle.getMessage(AnalyzeTextTopComponent.class, "HINT_AnalyzeTextTopComponent"));
    }



    void setComplexity(String complex) {
         lComplexity.setText("Word Scrambler has " + complex + " complexity.");
         boolean canAnalyze = new File(tfFile.getText()).exists();
         bAnalyze.setEnabled(canAnalyze);
         bUpload.setEnabled(false);
     }


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

        lFile = new javax.swing.JLabel();
        tfFile = new javax.swing.JTextField();
        bBrowse = new javax.swing.JButton();
        lComplexity = new javax.swing.JLabel();
        bAnalyze = new javax.swing.JButton();
        bUpload = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        lWords = new javax.swing.JList();

        org.openide.awt.Mnemonics.setLocalizedText(lFile, org.openide.util.NbBundle.getMessage(AnalyzeTextTopComponent.class, "AnalyzeTextTopComponent.lFile.text")); // NOI18N

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

        org.openide.awt.Mnemonics.setLocalizedText(bBrowse, org.openide.util.NbBundle.getMessage(AnalyzeTextTopComponent.class, "AnalyzeTextTopComponent.bBrowse.text")); // NOI18N
        bBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bBrowseActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(lComplexity, org.openide.util.NbBundle.getMessage(AnalyzeTextTopComponent.class, "AnalyzeTextTopComponent.lComplexity.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(bAnalyze, org.openide.util.NbBundle.getMessage(AnalyzeTextTopComponent.class, "AnalyzeTextTopComponent.bAnalyze.text")); // NOI18N
        bAnalyze.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAnalyzeActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(bUpload, org.openide.util.NbBundle.getMessage(AnalyzeTextTopComponent.class, "AnalyzeTextTopComponent.bUpload.text")); // NOI18N
        bUpload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bUploadActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(lWords);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 441, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(bAnalyze)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 160, Short.MAX_VALUE)
                        .add(bUpload, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 198, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(lComplexity, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 441, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(lFile)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(tfFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 286, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(18, 18, 18)
                        .add(bBrowse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(22, 22, 22))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lFile)
                    .add(tfFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(bBrowse, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .add(18, 18, 18)
                .add(lComplexity)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(bAnalyze)
                    .add(bUpload))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 148, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tfFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfFileActionPerformed
        
    }//GEN-LAST:event_tfFileActionPerformed

    private void bUploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bUploadActionPerformed
        // upload to Anagram Game
         WordLibrary wd = new AdditionalWordLibrary (scrambler.getWords(), scrambler.getScrambledWords());
         WordLibrary.setDefault(wd);
         bUpload.setEnabled(false);
         bAnalyze.setEnabled(false);


    }//GEN-LAST:event_bUploadActionPerformed

    private void bBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBrowseActionPerformed
        JFileChooser chooser = new JFileChooser();
         chooser.setFileSelectionMode (JFileChooser.FILES_ONLY);
         chooser.setMultiSelectionEnabled (false);
         chooser.setFileHidingEnabled (true);
         chooser.setDialogTitle ("Select a text file");
         if (chooser.showOpenDialog (this) == JFileChooser.APPROVE_OPTION) {
             textFile = chooser.getSelectedFile ();
             tfFile.setText(textFile.getPath());
             bAnalyze.setEnabled(true);
         }

    }//GEN-LAST:event_bBrowseActionPerformed

    private void bAnalyzeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAnalyzeActionPerformed
        File f = new File(tfFile.getText());
         if (! f.exists()) {
             NotifyDescriptor.Message nd = new NotifyDescriptor.Message
                     ("The file " + f.getPath() + " doesn't exist!", NotifyDescriptor.ERROR_MESSAGE);
             DialogDisplayer.getDefault().notify(nd);
             bUpload.setEnabled(false);
             bAnalyze.setEnabled(false);
             return;
         }
         String text = File2String.file2string(f);
         scrambler = new Scrambler(text, pref.getInt(ScramblerComplexityOptionsPanelController.SCRAMBLER_COMPLEXITY, 4));
         lWords.setListData(scrambler.getWords());
         bUpload.setEnabled(true);
         bAnalyze.setEnabled(false);
    }//GEN-LAST:event_bAnalyzeActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAnalyze;
    private javax.swing.JButton bBrowse;
    private javax.swing.JButton bUpload;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lComplexity;
    private javax.swing.JLabel lFile;
    private javax.swing.JList lWords;
    private javax.swing.JTextField tfFile;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized AnalyzeTextTopComponent getDefault() {
        if (instance == null) {
            instance = new AnalyzeTextTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the AnalyzeTextTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized AnalyzeTextTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(AnalyzeTextTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof AnalyzeTextTopComponent) {
            return (AnalyzeTextTopComponent) win;
        }
        Logger.getLogger(AnalyzeTextTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        AnalyzeTextTopComponent singleton = AnalyzeTextTopComponent.getDefault();
        singleton.readPropertiesImpl(p);
        return singleton;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }
}
