/* ////////////////////////////////////////////////////////////////
*
*   In the Name of Allah
*
*   DICTIONARYFORMIDS-CREATOR
*
*   This file is part of DictionaryForMIDs-Creator
*   Copyright (C) 2012 Karim Mahamane Karimou
*   DictionaryForMIDs-Creator is a GUI wrapper around various
*   DictionaryForMIDs tools, among others we have
*   DictdToDictionaryForMIDs, DictionaryGeneration,
*   JarCreator and BitmapFontGenerator.
*
*   DictionaryForMIDs-Creator is free software;
*   you can redistribute it and/or modify it under the terms
*   of the GNU General Public License as published by the
*   Free Software Foundation; either version 2 of the License, or
*   (at your option) any later version.
*
*   DictionaryForMIDs-Creator is distributed in the hope that
*   it will be useful, but WITHOUT ANY WARRANTY; without even
*   the implied warranty of MERCHANTABILITY or
*   FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public
*   License along with DictionaryForMIDs-Creator;
*   if not, write to the Free Software Foundation, Inc.,
*   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*
* //////////////////////////////////////////////////////////////// */


package de.kugihan.DfMCreator;

import de.kugihan.jarCreator.JarCreator;
import edu.hws.eck.mdb.I18n;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;


public class SumWinJarCreator extends javax.swing.JDialog implements PropertyChangeListener {

    private static final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    
    // This one is to make sure that the task
    // has been already created and launched.
    private static boolean taskFlag = false;

    public static SumWinJarCreator getJarCreatorSumWin(){
        SumWinJarCreator jcsw = new SumWinJarCreator();
        //cjpw.setSize(800, 600);
        jcsw.setLocation(screenSize.width / 2 - jcsw.getWidth() / 2,
                        screenSize.height / 2 - jcsw.getHeight() / 2);
        jcsw.setModal(true);
        return jcsw;
    }

    private Task task;
    public static boolean done;

    /**
     * Creates new form SumWinJarCreator
     */
    public SumWinJarCreator() {
        initComponents();
    }

    /**
     * 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel2 = new javax.swing.JPanel();
        StartBT = new javax.swing.JButton();
        CancelBT = new javax.swing.JButton();
        ProgBar = new javax.swing.JProgressBar();
        JarCreatorEnqueueBT = new javax.swing.JButton();
        JarCreatorClearQueueBT = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        JarCreatorSummaryTA = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        JarCreatorQueueTextArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(795, 595));
        setModal(true);
        setPreferredSize(new java.awt.Dimension(800, 600));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jPanel2.setLayout(new java.awt.GridBagLayout());

        StartBT.setText(I18n.tr("start.jarCreationSummary")); // NOI18N
        StartBT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StartBTActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 5;
        gridBagConstraints.ipady = 5;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel2.add(StartBT, gridBagConstraints);

        CancelBT.setText(I18n.tr("cancel.jarCreationSummary")); // NOI18N
        CancelBT.setEnabled(false);
        CancelBT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelBTActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 5;
        gridBagConstraints.ipady = 5;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel2.add(CancelBT, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 300;
        gridBagConstraints.ipady = 5;
        jPanel2.add(ProgBar, gridBagConstraints);

        JarCreatorEnqueueBT.setText(I18n.tr("enqueue.another.dict.JarCreator")); // NOI18N
        JarCreatorEnqueueBT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JarCreatorEnqueueBTActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 5;
        gridBagConstraints.ipady = 5;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel2.add(JarCreatorEnqueueBT, gridBagConstraints);

        JarCreatorClearQueueBT.setText(I18n.tr("clear.queue.contents.JarCreator")); // NOI18N
        JarCreatorClearQueueBT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JarCreatorClearQueueBTActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.ipadx = 5;
        gridBagConstraints.ipady = 5;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel2.add(JarCreatorClearQueueBT, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 200;
        gridBagConstraints.ipady = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jPanel2, gridBagConstraints);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        JarCreatorSummaryTA.setBackground(new java.awt.Color(254, 254, 254));
        JarCreatorSummaryTA.setColumns(20);
        JarCreatorSummaryTA.setEditable(false);
        JarCreatorSummaryTA.setLineWrap(true);
        JarCreatorSummaryTA.setRows(5);
        JarCreatorSummaryTA.setWrapStyleWord(true);
        jScrollPane2.setViewportView(JarCreatorSummaryTA);
        fillJarCreationSummaryTextArea();

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 200;
        gridBagConstraints.ipady = 300;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jScrollPane2, gridBagConstraints);

        JarCreatorQueueTextArea.setBackground(new java.awt.Color(232, 232, 232));
        JarCreatorQueueTextArea.setColumns(20);
        JarCreatorQueueTextArea.setEditable(false);
        JarCreatorQueueTextArea.setLineWrap(true);
        JarCreatorQueueTextArea.setRows(5);
        JarCreatorQueueTextArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(JarCreatorQueueTextArea);
        fillJarCreatorQueueTA();

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 30;
        gridBagConstraints.ipady = 300;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
        jPanel1.add(jScrollPane1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 2.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jPanel1, gridBagConstraints);

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

    private void StartBTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartBTActionPerformed
        executeJarCreationTask();
    }//GEN-LAST:event_StartBTActionPerformed

    private void CancelBTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelBTActionPerformed
        confirmCancelConvert();
    }//GEN-LAST:event_CancelBTActionPerformed

    private void JarCreatorEnqueueBTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JarCreatorEnqueueBTActionPerformed
        this.dispose();
        DfMCreatorMain.dfmCreator.clearJarCreatorTFsExceptEmptyDfM();
    }//GEN-LAST:event_JarCreatorEnqueueBTActionPerformed

    private void JarCreatorClearQueueBTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JarCreatorClearQueueBTActionPerformed
        clearJarCreatorQueueContents();
    }//GEN-LAST:event_JarCreatorClearQueueBTActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        cancelJarCreationOnQuit();
        DfMCreatorMain.dfmCreator.clearJarCreatorTFsExceptEmptyDfM();
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /*
         * Set the default look and feel
         */

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        try {
             javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException |
        		 IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DfMCreatorMain.class.getName()).
            log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
              //  new SumWinJarCreator().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelBT;
    private javax.swing.JButton JarCreatorClearQueueBT;
    private javax.swing.JButton JarCreatorEnqueueBT;
    private javax.swing.JTextArea JarCreatorQueueTextArea;
    private javax.swing.JTextArea JarCreatorSummaryTA;
    private javax.swing.JProgressBar ProgBar;
    private javax.swing.JButton StartBT;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables

    private static final String newline = "\n";


    private void cancelJarCreationOnQuit() {
        if (taskFlag){
            if (!task.isDone()){
                task.cancel(true);
                deleteIncompleteDictFile();
            }
        }
        DfMCreatorMain.dfmCreator.jarCreatorQueue.clear();
        DfMCreatorMain.dfmCreator.jarCreatorArray.clear();
    }

    class Task extends SwingWorker<Void, Void> {
        @Override
        public Void doInBackground() {
            DfMCreatorMain.JarCreatorValsToEnqueue q;
            try {
                    // This is for the queue itself
                    while (!DfMCreatorMain.dfmCreator.jarCreatorQueue.isEmpty()){
                        q = DfMCreatorMain.dfmCreator.jarCreatorQueue.remove();

                        // Passing the values of the current item
                        // to JarCreator in order for it to process it
                        JarCreator jc = new JarCreator();
                        JarCreator.setDictionaryDirectory(q.dictDir);
                        JarCreator.setEmptyDictionaryForMID(q.emptyDfM);
                        JarCreator.setOutputDirectory(q.outputDir);

                        // Showing the jar creation preferences
                        // for the current item being processed.
                        JarCreatorSummaryTA.setText("");

                        JarCreatorSummaryTA.append(I18n.tr("items.info.jarCreator") + "\n\n");
                        JarCreatorSummaryTA.append(I18n.tr("remaining.items.jarCreator"));
                        JarCreatorSummaryTA.append(String.valueOf(DfMCreatorMain.dfmCreator.jarCreatorQueue.size()) + "\n\n");
                        JarCreatorSummaryTA.append(I18n.tr("dictDir.jarCreationSummary") + "\n");
                        JarCreatorSummaryTA.append(q.dictDir + "\n\n");

                        JarCreatorSummaryTA.append(I18n.tr("emptyDfMDir.jarCreationSummary") + "\n");
                        JarCreatorSummaryTA.append(q.emptyDfM + "\n\n");

                        JarCreatorSummaryTA.append(I18n.tr("outputDir.jarCreationSummary") + "\n");
                        JarCreatorSummaryTA.append(q.outputDir + "\n");

                        // Perform the Jar Creation for
                        // the current item.
                        jc.createJar();

                        // Update the contents of the TextArea that displays the items
                        // to be processed as some are being removed from the queue
                        // JarCreatorSummaryTA
                        int i = 0;
                        DfMCreatorMain.dfmCreator.jarCreatorArray.remove(i);
                        JarCreatorQueueTextArea.setText("");
                        JarCreatorQueueTextArea.append(I18n.tr("items.queue.JarCreator") + "\n\n");
                        for (int j=0; j<DfMCreatorMain.dfmCreator.jarCreatorArray.size(); j++){
                            JarCreatorQueueTextArea.append(DfMCreatorMain.dfmCreator.jarCreatorArray.get(j).toString() + "\n");
                        }

                    }

            } catch (DfMCreatorException.CantCreatOutputJarJadDirectory e){
                done = true;
                DfMCreatorMain.printAnyMsg(e.getMessage() ,"Directory Creation Error", JOptionPane.ERROR_MESSAGE);
                System.out.println(e.getMessage());
            } catch (Throwable t) {
                done = true;
                DfMCreatorMain.printAnyMsg(I18n.tr("unknownRuntimeError.dfmCreatorMain",
                    new Object[] {t, t.getLocalizedMessage()}),
                    I18n.tr("unknownRuntimeErrorTitle"), JOptionPane.ERROR_MESSAGE);
                System.out.println(t + "\n\n");
            }
            return null;
        }

        @Override
        public void done() {
            //Tell progress listener to stop updating progress bar.
            done = true;
            StartBT.setEnabled(true);
            CancelBT.setEnabled(false);
            JarCreatorEnqueueBT.setEnabled(true);
            JarCreatorClearQueueBT.setEnabled(false);
            Toolkit.getDefaultToolkit().beep();
            setCursor(null); //turn off the wait cursor
            ProgBar.setIndeterminate(false);
            ProgBar.setValue(ProgBar.getMinimum());
            JarCreatorSummaryTA.append(I18n.tr("done.jarCreationSummary"));
        }
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (!done) {
            int progress = task.getProgress();
            if (progress == 0) {
                ProgBar.setStringPainted(false);
                ProgBar.setIndeterminate(true);
                JarCreatorSummaryTA.append(I18n.tr("pleaseWait.jarCreationSummary"));
                StartBT.setEnabled(false);
                CancelBT.setEnabled(true);
            }
            else {
                ProgBar.setIndeterminate(false);
                ProgBar.setString(null);
                ProgBar.setValue(progress);
                JarCreatorSummaryTA.append(String.format(newline + newline +
                I18n.tr("completed.jarCreationSummary"), task.getProgress()));
            }
        }
    }

    public void executeJarCreationTask(){
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        StartBT.setEnabled(false);
        CancelBT.setEnabled(true);
        JarCreatorEnqueueBT.setEnabled(false);
        //JarCreatorClearQueueBT.setEnabled(false);
        done = false;
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
        ProgBar.setValue(task.getProgress());
        // Tell that the task has been lauched.
        taskFlag = true;
      }

    public void confirmCancelConvert() {
        int n = JOptionPane.showConfirmDialog(null, I18n.tr("sureToCancelConversion.jarCreationSummary"),
                                      I18n.tr("cancelConversion.jarCreationSummary"), JOptionPane.YES_NO_OPTION);
        if (n == JOptionPane.YES_OPTION){
            if (!task.isDone()){
                task.cancel(true);
                deleteIncompleteDictFile();
                DfMCreatorMain.dfmCreator.jarCreatorQueue.clear();
                DfMCreatorMain.dfmCreator.jarCreatorArray.clear();
            }
        }
    }

    // deletes the incomplete jar and jad files
    // if the user aborts the operation
    public void deleteIncompleteDictFile(){
        if (JarCreator.jarFlag){
            File incompleteJar = JarCreator.getJarFile();
            if (incompleteJar.exists()) {
                incompleteJar.delete();
            }
        }

        if (JarCreator.jadFlag){
            File incompleteJad = JarCreator.getJadFile();
            if (incompleteJad.exists()) {
                incompleteJad.delete();
            }
        }
    }

    /**
     * fillJarCreationSummaryTextArea() gets all the needed information
     * and formats them correctly so as to have a clear and neat
     * summary of the Jar Creation preferences entered
     * by the user.
     */
    private void fillJarCreationSummaryTextArea() {

        JarCreatorSummaryTA.setText("");
        JarCreatorSummaryTA.append(I18n.tr("headLine.jarCreationSummary") + "\n");

        JarCreatorSummaryTA.append(I18n.tr("dictDir.jarCreationSummary"));
        JarCreatorSummaryTA.append("\n" + JarCreator.getDictionaryDirectory() + "\n\n");

        JarCreatorSummaryTA.append(I18n.tr("emptyDfMDir.jarCreationSummary"));
        JarCreatorSummaryTA.append("\n" + JarCreator.getEmptyDictionaryForMID() + "\n\n");

        JarCreatorSummaryTA.append(I18n.tr("outputDir.jarCreationSummary"));
        JarCreatorSummaryTA.append("\n" + JarCreator.getOutputDirectory() + "\n\n");

        JarCreatorSummaryTA.append(I18n.tr("hitStart.jarCreationSummary"));
        JarCreatorSummaryTA.append("\n");
    }

    private void clearJarCreatorQueueContents() {
        DfMCreatorMain.dfmCreator.jarCreatorQueue.clear();
        DfMCreatorMain.dfmCreator.jarCreatorArray.clear();
        JarCreatorQueueTextArea.setText("");
        JarCreatorSummaryTA.setText("");
        DfMCreatorMain.dfmCreator.clearJarCreatorTFsExceptEmptyDfM();
    }

    private void fillJarCreatorQueueTA() {
        JarCreatorQueueTextArea.setText("");
        JarCreatorQueueTextArea.append(I18n.tr("items.queue.JarCreator") + "\n\n");
        for (int i=0; i<DfMCreatorMain.dfmCreator.jarCreatorArray.size(); i++){
            JarCreatorQueueTextArea.append(DfMCreatorMain.dfmCreator.jarCreatorArray.get(i).toString() + "\n");
        }
    }

}
