/*
 * TessFrame.java
 *
 * Created on 31 luglio 2008, 13.59
 */
package tessgui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

/**
 *
 * @author  marius (http://www.spinu.it)
 * @email   marius@spinu.it
 */
public class TessFrame extends javax.swing.JFrame {

    String tesseractPath = "";
    List<File> selectedFiles;

    /** Creates new form TessFrame
     * @param tessPath 
     */
    public TessFrame(String tessPath) {
        selectedFiles = new ArrayList<File>();
        this.tesseractPath = tessPath;
        initComponents();
        tessPathTextField.setText(tesseractPath);
    }

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

        cfgPanel = new javax.swing.JPanel();
        tessPathTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        changePathButton = new javax.swing.JButton();
        outputFileNameLabel = new javax.swing.JLabel();
        outputFileNameTextField = new javax.swing.JTextField();
        fileListPanel = new javax.swing.JPanel();
        fileList = new java.awt.List();
        buttonPanel = new javax.swing.JPanel();
        runButton = new javax.swing.JButton();
        addFileButton = new javax.swing.JButton();
        removeAllButton = new javax.swing.JButton();
        quitButton4 = new javax.swing.JButton();
        aboutButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        logPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        logTextArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Tesseract Installation Path");

        changePathButton.setText("...");
        changePathButton.setToolTipText("Change Tesseract Installation Path");
        changePathButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changePathButtonActionPerformed(evt);
            }
        });

        outputFileNameLabel.setText("Output File Name");

        outputFileNameTextField.setText("= FileName.txt");
        outputFileNameTextField.setEnabled(false);

        javax.swing.GroupLayout cfgPanelLayout = new javax.swing.GroupLayout(cfgPanel);
        cfgPanel.setLayout(cfgPanelLayout);
        cfgPanelLayout.setHorizontalGroup(
            cfgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(cfgPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(cfgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(outputFileNameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(cfgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(outputFileNameTextField)
                    .addComponent(tessPathTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(changePathButton)
                .addContainerGap(34, Short.MAX_VALUE))
        );
        cfgPanelLayout.setVerticalGroup(
            cfgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(cfgPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(cfgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(changePathButton)
                    .addComponent(tessPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(cfgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(outputFileNameLabel)
                    .addComponent(outputFileNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jLabel1.getAccessibleContext().setAccessibleName("tessPathLabel");
        changePathButton.getAccessibleContext().setAccessibleName("changePathButton");

        javax.swing.GroupLayout fileListPanelLayout = new javax.swing.GroupLayout(fileListPanel);
        fileListPanel.setLayout(fileListPanelLayout);
        fileListPanelLayout.setHorizontalGroup(
            fileListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fileList, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)
        );
        fileListPanelLayout.setVerticalGroup(
            fileListPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fileList, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
        );

        buttonPanel.setBackground(new java.awt.Color(204, 204, 255));

        runButton.setText("RUN");
        runButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                runButtonActionPerformed(evt);
            }
        });

        addFileButton.setText("ADD FILE");
        addFileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addFileButtonActionPerformed(evt);
            }
        });

        removeAllButton.setText("REMOVE ALL");
        removeAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeAllButtonActionPerformed(evt);
            }
        });

        quitButton4.setText("QUIT");
        quitButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitButton4ActionPerformed(evt);
            }
        });

        aboutButton.setText("About");
        aboutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutButtonActionPerformed(evt);
            }
        });

        jLabel2.setForeground(new java.awt.Color(102, 102, 255));
        jLabel2.setText("TessGUI-v0-20");

        javax.swing.GroupLayout buttonPanelLayout = new javax.swing.GroupLayout(buttonPanel);
        buttonPanel.setLayout(buttonPanelLayout);
        buttonPanelLayout.setHorizontalGroup(
            buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                .addComponent(runButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addFileButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(removeAllButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(quitButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(aboutButton)
                .addGap(46, 46, 46))
        );
        buttonPanelLayout.setVerticalGroup(
            buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(buttonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(runButton)
                        .addComponent(addFileButton)
                        .addComponent(removeAllButton)
                        .addComponent(quitButton4)
                        .addComponent(aboutButton))
                    .addComponent(jLabel2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        logTextArea.setColumns(20);
        logTextArea.setForeground(java.awt.SystemColor.textInactiveText);
        logTextArea.setRows(5);
        jScrollPane1.setViewportView(logTextArea);

        javax.swing.GroupLayout logPanelLayout = new javax.swing.GroupLayout(logPanel);
        logPanel.setLayout(logPanelLayout);
        logPanelLayout.setHorizontalGroup(
            logPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 556, Short.MAX_VALUE)
            .addGroup(logPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE))
        );
        logPanelLayout.setVerticalGroup(
            logPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 160, Short.MAX_VALUE)
            .addGroup(logPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(logPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(buttonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(cfgPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(fileListPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(cfgPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fileListPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(logPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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

private void quitButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitButton4ActionPerformed
    System.exit(0);
}//GEN-LAST:event_quitButton4ActionPerformed

private void addFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFileButtonActionPerformed
    JFileChooser chooser = new JFileChooser();
    //chooser.addChoosableFileFilter(new FileNameExtensionFilter("File XML", "xml"));
    int x = JFileChooser.FILES_ONLY;
    chooser.setCurrentDirectory(new File(tesseractPath));
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File f = chooser.getSelectedFile();
        // qui viene eseguita l'operazione sul file
        selectedFiles.add(f);
        updateShowedList();
    }
}//GEN-LAST:event_addFileButtonActionPerformed

private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed
// TODO add your handling code here:
    selectedFiles.clear();
    updateShowedList();
}//GEN-LAST:event_removeAllButtonActionPerformed

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed
// TODO add your handling code here:
    for (File fs : selectedFiles) {
        String executeCom = tesseractPath + "\\tesseract.exe " + fs.getAbsolutePath() + " " + tesseractPath + "\\" + fs.getName().subSequence(0, (fs.getName().length() - 4)) + "";
        System.out.println(" --- " + executeCom);
        try {
            logTextArea.append("Starting tesseract for: \n" + fs.getName() + "\n");
            Process p = Runtime.getRuntime().exec(executeCom);
            p.waitFor();
            if (p.exitValue() == 0) {
                logTextArea.append("Done: \n" + fs.getName().subSequence(0, (fs.getName().length() - 4)) + ".txt \n");
            } else {
                logTextArea.append("Errors for: \n" + fs.getName().subSequence(0, (fs.getName().length() - 4)) + ".txt \n");
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(TessFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TessFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}//GEN-LAST:event_runButtonActionPerformed

private void aboutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutButtonActionPerformed
// TODO add your handling code here:
    AboutDlg adlg = new AboutDlg(this, true);
    adlg.setVisible(true);

}//GEN-LAST:event_aboutButtonActionPerformed

private void changePathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changePathButtonActionPerformed
// TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Select Tesseract Path");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setCurrentDirectory(new File(tesseractPath));
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        tesseractPath = chooser.getSelectedFile().getAbsolutePath();
        tessPathTextField.setText(tesseractPath);
    }

}//GEN-LAST:event_changePathButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aboutButton;
    private javax.swing.JButton addFileButton;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JPanel cfgPanel;
    private javax.swing.JButton changePathButton;
    private java.awt.List fileList;
    private javax.swing.JPanel fileListPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel logPanel;
    private javax.swing.JTextArea logTextArea;
    private javax.swing.JLabel outputFileNameLabel;
    private javax.swing.JTextField outputFileNameTextField;
    private javax.swing.JButton quitButton4;
    private javax.swing.JButton removeAllButton;
    private javax.swing.JButton runButton;
    private javax.swing.JTextField tessPathTextField;
    // End of variables declaration//GEN-END:variables
    private void updateShowedList() {
        fileList.removeAll();
        for (File fs : selectedFiles) {
            fileList.add(fs + "");
        }
    }

    private void updateLog() {
        String fileLogName = tesseractPath + "\\tesseract.log";
        File tessLog = new File(fileLogName);
        FileReader fRed;
        String s = "";
        if (tessLog.canRead()) {
            try {
                fRed = new FileReader(fileLogName);
                BufferedReader in = new BufferedReader(fRed);
                while ((s = in.readLine()) != null) {
                    logTextArea.append(s + "\n");
                }
            } // Catches any error conditions
            catch (IOException e) {
                System.err.println("Unable to read from file");
                System.exit(-1);
            }

        }
    }
}
