package turgen.plugin;

import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
import turgen.Utils;
import turgen.dtb.DOS2Binary;
import turgen.dtb.DOS2BinaryException;

/**
 * Silence list panel
 */
public class SilenceListPanel extends javax.swing.JPanel {

    private InOutProvider ioProvider;
    
    public SilenceListPanel() {
        ioProvider=null;
        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;

        jtfSilenceList = new javax.swing.JTextField();
        jbtSilence = new javax.swing.JButton();
        jbtPauses = new javax.swing.JButton();
        jspiDefaultLength = new javax.swing.JSpinner();

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

        jtfSilenceList.setColumns(32);
        jtfSilenceList.setToolTipText("<HTML>\nEnter comma-separated list of silence specifications<br>\nEach silence specification will be used to generate silence or pause the signal generator after an INIT segment<br><br>\nSilence specification can be the following:<br>\nNumber of seconds (e.g. <b>3</b>)<br>\nNumber of seconds followed by P (e.g. <b>3P</b>)<br>\nP (e.g. <b>P</b>)\n</HTML>");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.weightx = 1.0;
        add(jtfSilenceList, gridBagConstraints);

        jbtSilence.setText("S");
        jbtSilence.setToolTipText("Silence");
        jbtSilence.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jbtSilence.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onAddSilence(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        add(jbtSilence, gridBagConstraints);

        jbtPauses.setText("P");
        jbtPauses.setToolTipText("Pauses");
        jbtPauses.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jbtPauses.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onAddSilence(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        add(jbtPauses, gridBagConstraints);

        jspiDefaultLength.setModel(new javax.swing.SpinnerNumberModel(1, 1, 60, 1));
        jspiDefaultLength.setToolTipText("Silence duration");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        add(jspiDefaultLength, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void onAddSilence(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onAddSilence
        boolean pauses = (evt.getSource()==jbtPauses);
        if (ioProvider==null) return;
        
        String inFilespec = ioProvider.getInFile();
        File f = new File(inFilespec);
        
        /*Check existence*/
        if (!f.exists()) {
            JOptionPane.showMessageDialog(null, "Unable to populate the silence list: Input file does not exist", "File does not exist", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        /*Check if regular file*/
        if (!f.isFile()) {
            JOptionPane.showMessageDialog(null, "Unable to populate the silence list: Input file is not a regular file", "File is not a regular file", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        /*Check if binary file*/
        DOS2Binary dtb = new DOS2Binary(inFilespec);
        try {
            dtb.analyzeFromFile();
        }
        catch (IOException e) {
            JOptionPane.showMessageDialog(null, Utils.getExceptionMessage(e), "Binary file error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        catch (DOS2BinaryException d2be) {
            JOptionPane.showMessageDialog(null,d2be.getFormattedMessage(true,"Unable to populate silence list"),"Binary file error",JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        int numInitSegments = dtb.getInitLocations().length;
        jtfSilenceList.setText("");
        
        /*Determine string form of silence duration*/
        Integer duration = (Integer)jspiDefaultLength.getValue();
        String durationString = duration.toString();
        if (pauses==true) {
            durationString+="P";
        }
        
        StringBuilder sb = new StringBuilder();
        
        for(int i=0;i<numInitSegments;i++) {
            sb.append(durationString);
            if (i<numInitSegments-1) {
                sb.append(',');
            }
        }
        
        jtfSilenceList.setText(sb.toString());
    }//GEN-LAST:event_onAddSilence


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbtPauses;
    private javax.swing.JButton jbtSilence;
    private javax.swing.JSpinner jspiDefaultLength;
    private javax.swing.JTextField jtfSilenceList;
    // End of variables declaration//GEN-END:variables
    
    
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        
        jtfSilenceList.setEnabled(enabled);
        jspiDefaultLength.setEnabled(enabled);
        jbtPauses.setEnabled(enabled);
        jbtSilence.setEnabled(enabled);
        
    }
    
    /** Set input and output file provider
     * 
     * @param provider Input and output file provider
     */
    public void setIOProvider(InOutProvider provider) {
        ioProvider = provider;
    }
    
    /** Clear panel*/
    public void clear() {
        jtfSilenceList.setText("");
    }
    /** Get silence list string
     * 
     * @return Silence list string
     */
    public String getSilenceListString() {
        return jtfSilenceList.getText();
    }
    /** Set silence list string
     * 
     * @param silenceListString Silence list string
     */
    public void setSilenceListString(String silenceListString) {
        jtfSilenceList.setText(silenceListString);
    }
    
    
    
}
