package turgen.plugin.plturbo;

import turgen.plugin.csturbo.*;
import turgen.plugin.*;
import javax.swing.*;
import java.io.*;
import turgen.dtb.DOS2Binary;
import turgen.Utils;

public class PlASTPluginPanel extends javax.swing.JPanel {
    
    
    InOutProvider ioProvider;
    
    
    /** Creates new PlTurboROMPluginPanel */
    public PlASTPluginPanel() {
        initComponents();
        setupToolTips();
    }
    
    /** 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        jrbgHandling = new javax.swing.ButtonGroup();
        pTHeader = new javax.swing.JPanel();
        jtfName = new javax.swing.JTextField();
        jlbName = new javax.swing.JLabel();
        btnGuessHeader = new javax.swing.JButton();
        pHandling = new javax.swing.JPanel();
        jcoConversionType = new javax.swing.JComboBox();
        btnCheckLoader = new javax.swing.JButton();
        pOther = new javax.swing.JPanel();
        jlbPauses = new javax.swing.JLabel();
        jtfPauses = new javax.swing.JTextField();
        pFiller = new javax.swing.JPanel();

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

        pTHeader.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pTHeader.setLayout(new java.awt.GridBagLayout());

        jtfName.setColumns(22);
        jtfName.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
        jtfName.setToolTipText("File name");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.2;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 0);
        pTHeader.add(jtfName, gridBagConstraints);

        jlbName.setText("File name:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 0);
        pTHeader.add(jlbName, gridBagConstraints);

        btnGuessHeader.setMnemonic('h');
        btnGuessHeader.setText("Auto set header");
        btnGuessHeader.setToolTipText("<HTML>\nAutomatically fill the turbo header using:<BR>\n1.Analysis of input file<BR>\n2.Selected conversion type<BR>\n</HTML>\n\n");
        btnGuessHeader.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                on_guess_header(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weighty = 0.2;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 0);
        pTHeader.add(btnGuessHeader, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        add(pTHeader, gridBagConstraints);

        pHandling.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Conversion type"));
        pHandling.setLayout(new java.awt.GridBagLayout());

        jcoConversionType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AST", "BUT" }));
        jcoConversionType.setToolTipText("Choose conversion type according to the type of the input file");
        jcoConversionType.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                on_cvTypeChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 4, 2, 0);
        pHandling.add(jcoConversionType, gridBagConstraints);

        btnCheckLoader.setMnemonic('c');
        btnCheckLoader.setText("Check loader");
        btnCheckLoader.setEnabled(false);
        btnCheckLoader.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCheckLoaderActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        pHandling.add(btnCheckLoader, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        add(pHandling, gridBagConstraints);

        pOther.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Binary file"));
        pOther.setLayout(new java.awt.GridBagLayout());

        jlbPauses.setText("Silence list:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 0);
        pOther.add(jlbPauses, gridBagConstraints);

        jtfPauses.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
        jtfPauses.setToolTipText("<HTML>\nPlace <b>comma-separated list of numebrs</b> here. <br>\nEach number is <b>length of silence</b> (in seconds) generated <b>after INIT segments.</b><br>\nThis is useful only if the MOTOR CTRL signal is ignored by device you are using.<br>\n</HTML>");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        pOther.add(jtfPauses, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
        add(pOther, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weighty = 1.0;
        add(pFiller, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents
    
    private void on_guess_header(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_on_guess_header

        /*What conversion type was selected*/
        int idx = this.jcoConversionType.getSelectedIndex();
        /*Clearing text fields*/
        jtfName.setText("");

        /*Testing existence*/
        File f = new File(ioProvider.getInFile());
        /*Testing existence*/
        String msg = Utils.checkIfHeaderCanBeSet(f);
        if (msg!=null) {
            JOptionPane.showMessageDialog(null, msg,"Unable to set header",JOptionPane.ERROR_MESSAGE);
            return;
        }

        /*File name*/
        String fn=f.getName();
        if (fn.length()>20) fn=fn.substring(0,20);

        /*Setting header according to conversion type*/
        switch (idx) {

            /*AST compatible binary file*/
            case PlASTPlaylistItem.CV_BINARY_AST: {

                DOS2Binary dtb = new DOS2Binary(ioProvider.getInFile());
                try {
                    dtb.analyzeFromFile();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, Utils.getTitledExceptionMessage("Unable to set header", e),"Unable to set header",JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (verifyASTCompatible()==false) {
                    JOptionPane.showMessageDialog(this, AST_NCOMP_MSG, "Warning", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                break;
            }
        }

    /*File name is common*/
    jtfName.setText(fn);
    

    }//GEN-LAST:event_on_guess_header

    private void on_cvTypeChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_on_cvTypeChanged

        if (jcoConversionType.getSelectedIndex()==0) {
            btnCheckLoader.setEnabled(false);
        }
        else {
            btnCheckLoader.setEnabled(true);
        }
    }//GEN-LAST:event_on_cvTypeChanged

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

        String message = Utils.checkForBinaryLoader(ioProvider.getInFile(), 0x786, 0x889, 0x786, 0x889, 254);
        JOptionPane.showMessageDialog(null, message,"Loader check",JOptionPane.INFORMATION_MESSAGE);

    }//GEN-LAST:event_btnCheckLoaderActionPerformed
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCheckLoader;
    private javax.swing.JButton btnGuessHeader;
    private javax.swing.JComboBox jcoConversionType;
    private javax.swing.JLabel jlbName;
    private javax.swing.JLabel jlbPauses;
    private javax.swing.ButtonGroup jrbgHandling;
    private javax.swing.JTextField jtfName;
    private javax.swing.JTextField jtfPauses;
    private javax.swing.JPanel pFiller;
    private javax.swing.JPanel pHandling;
    private javax.swing.JPanel pOther;
    private javax.swing.JPanel pTHeader;
    // End of variables declaration//GEN-END:variables
    
    
    void clear() {
        jtfName.setText("");
        jcoConversionType.setSelectedIndex(0);
    }
    
    
    public PlASTPlaylistItem getRecord() {
        PlASTPlaylistItem trpi = new PlASTPlaylistItem(ioProvider.getInFile(),ioProvider.getOutFile(),ioProvider.getPulses(),jtfName.getText(),jcoConversionType.getSelectedIndex(),Utils.parseNumberList(jtfPauses.getText().trim()));
        return trpi;
    }
    
    
    public void fill(PlASTPlaylistItem trpi) {
        jtfName.setText(trpi.fname);
        jcoConversionType.setSelectedIndex(trpi.conversionType);
        jtfPauses.setText(Utils.createNumberList(trpi.silenceList));

    }
    
    public String verify() {

        if (jcoConversionType.getSelectedIndex()==PlASTPlaylistItem.CV_BINARY_AST) {
            if (verifyASTCompatible()==false) {
                return AST_NCOMP_MSG;
            }
        }
        return null;
    }
    
    
    private void setupToolTips() {
        
    }

    boolean verifyASTCompatible() {

         /*Load and analyze file*/
        DOS2Binary ae = new DOS2Binary(ioProvider.getInFile());
        try {
            ae.analyzeFromFile();
        }
        catch (Exception e) {
            return true;
        }

        /*Check number of segments*/
        if (ae.getTotalSegmentCount()>44 || ae.hasInitSegment()==true) return false; else return true;

    }

    private static final String AST_NCOMP_MSG=
            "<HTML>"+
            "Input binary file cannot be converted to the AST format, because<BR>"+
            "it contains more than 44 segments or contains an INIT segment.<BR><BR>"+
            "To convert the binary file, use the <U>BUT</U> conversion type.</HTML>";
}


   



