package de.nplusc.upidgen;





import de.nplusc.izc.tools.IOtools.DBWriter;
import de.nplusc.izc.tools.baseTools.Tools;
import java.util.HashMap;

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

/**
 *
 * @author LH
 */
public class UPIDAssistant extends javax.swing.JFrame
{
    /**
     * Creates new form UPIDAssistant
     */
    
    
    
    private static DBWriter dbc = PublicStorage.dbc;
    public void clearList()
    {
        lstOpt.removeAll();
        
        boolean lext = true;
        while(lext)
        {
            try{
            //lstOpt.remove(0);
            ((javax.swing.DefaultListModel)lstOpt.getModel()).removeElementAt(0);
            }
            catch(Exception e)
            {
                lext=false;
            }
        }
        ((javax.swing.DefaultListModel)lstOpt.getModel()).removeAllElements();
    }
    
    public UPIDAssistant()
    {
        initComponents();
        rebuildLST(0);
        lblMsg.setText("");
        txfManualInput.setVisible(false);
        lstOpt.setVisible(true);
        lblMsg.setVisible(false);
        progressOfAssist.setMinimum(0);
        progressOfAssist.setMaximum(5);
    }
    
    public HashMap<String,String> getMfids()
    {
        HashMap<String,String> ret = new HashMap<>();
        String[][] mfidtable = dbc.queryTable("select * from mfids" , 2);
        for (String[] line : mfidtable)
        {
                ret.put(line[0],line[1]);
        }
                        
           //<editor-fold defaultstate="collapsed" desc=" Fail">     
       /*         
                
    HashMap<String,String> ret = new HashMap<>();
    Connection cn = null;
    Statement  st = null;
    ResultSet  rs = null;
    try {
      // Select fitting database driver and connect:
      Class.forName("com.mysql.jdbc.Driver");
      cn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/upidtk","root","");
      st = cn.createStatement();
      rs = st.executeQuery( "select * from mfids" );
    
      String mfid,desc;
        if(rs!=null)
        {
            while(rs.next())
            {
                
                mfid = rs.getString(1);
                desc = rs.getString(2);
                ret.put(mfid,desc);
            }
            rs.close();
        }
    }
        catch (Exception e)
    {
        
    }*/
        //</editor-fold>
        return ret;
    }
    public HashMap<String,String> getPSC(String LMFID)//Wenn PSC = -- dann freie Eingabe erforderlich. Desc enthält dann den BEschreibungstext
    {
        
        HashMap<String,String> ret = new HashMap<>();
        String[][] mfidtable = dbc.queryTable( "select PSC,Descrip from psc where MFID like '"+LMFID+"'" , 2);
        for (String[] line : mfidtable)
        {
                ret.put(line[0],line[1]);
        }
        return ret;
         //<editor-fold defaultstate="collapsed" desc=" Fail">   
    /*
    
    Connection cn = null;
    Statement  st = null;
    ResultSet  rs = null;
    try {
      // Select fitting database driver and connect:
      Class.forName("com.mysql.jdbc.Driver");
      cn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/upidtk","root","");
      st = cn.createStatement();
      rs = st.executeQuery( "select PSC,Descrip from psc where MFID like '"+LMFID+"'" );
    
      String psc,desc;
        if(rs!=null)
        {
            while(rs.next())
            {
                
                psc = rs.getString(1);
                desc = rs.getString(2);
                ret.put(psc,desc);
            }
            rs.close();
        }
    }
        catch (Exception e)
    {
        
    }
        return ret;*/
        //</editor-fold>
    }
    public HashMap<String,String> getSrcs()
    {
        
        
                
        HashMap<String,String> ret = new HashMap<>();
        String[][] mfidtable = dbc.queryTable( "select value,name from srcs" , 2);
        for (String[] line : mfidtable)
        {
            
                String tmp=line[0];

                String lsrc = Tools.padLeft(2, tmp, '0');
                String desc = line[1];
                ret.put(lsrc,desc);
        }
        return ret;
         //<editor-fold defaultstate="collapsed" desc=" Fail">   
        /*
    HashMap<String,String> ret = new HashMap<>();
    Connection cn = null;
    Statement  st = null;
    ResultSet  rs = null;
    try {
      // Select fitting database driver and connect:
      Class.forName("com.mysql.jdbc.Driver");
      cn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/upidtk","root","");
      st = cn.createStatement();
      rs = st.executeQuery( "select value,name from srcs" );
      String src;
      String desc;
        if(rs!=null)
        {
            while(rs.next())
            {
                String tmp=rs.getString(1);

                src = Tools.padLeft(2, tmp, '0');
                desc = rs.getString(2);
                ret.put(src,desc);
            }
            rs.close();
        }
    }
        catch (Exception e)
    {
        //System.err.println("Verfotzte Scheisse");
        //e.printStackTrace();
    }
        return ret;*/
        //</editor-fold>
    }
    /**
     * 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() {

        jSeparator2 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstOpt = new javax.swing.JList();
        btnContinue = new javax.swing.JButton();
        progressOfAssist = new javax.swing.JProgressBar();
        txfManualInput = new javax.swing.JTextField();
        lblMsg = new javax.swing.JLabel();
        slZSC = new javax.swing.JSlider();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator3 = new javax.swing.JSeparator();
        jSeparator4 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lstOpt.setModel(new javax.swing.DefaultListModel()/*AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        }*/);
        jScrollPane1.setViewportView(lstOpt);

        btnContinue.setText("Weiter>>");
        btnContinue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnContinueActionPerformed(evt);
            }
        });

        progressOfAssist.setMaximum(7);

        lblMsg.setText("lblShouldntbeVIsible//\\\\Used as MessageOutput");

        slZSC.setMajorTickSpacing(10);
        slZSC.setMaximum(99);
        slZSC.setMinorTickSpacing(1);
        slZSC.setPaintTicks(true);
        slZSC.setSnapToTicks(true);
        slZSC.setValue(0);
        slZSC.setPreferredSize(new java.awt.Dimension(600, 33));

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(progressOfAssist, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnContinue))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(slZSC, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblMsg, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 571, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txfManualInput))
                                .addGap(7, 7, 7)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addComponent(lblMsg)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(slZSC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txfManualInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(19, 19, 19)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                        .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnContinue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(progressOfAssist, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

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

    private void rebuildLST(int stg)
    {
        slZSC.setVisible(false);
        clearList();
        if(stg==0)
        {
           
            HashMap<String,String> mfidsel = getMfids();
            String[] keys = mfidsel.keySet().toArray(new String[0]);
            for (String string : keys)
            {
                String val = mfidsel.get(string);
                ((javax.swing.DefaultListModel)lstOpt.getModel()).addElement(string+"|"+val);
            }
        }
        if(stg==1)
        {
            HashMap<String,String> psc = getPSC(MFID);
            String[] psca = psc.keySet().toArray(new String[0]);
            if(psca[0].equals("--"))
            {
                txfManualInput.setVisible(true);
                lstOpt.setVisible(false);
                jScrollPane1.setVisible(false);
                lblMsg.setVisible(true);
                lblMsg.setText(psc.get("--"));
                freetype=true;
            }
            else
            {
                txfManualInput.setVisible(false);
                lstOpt.setVisible(true);
                jScrollPane1.setVisible(true);
                lblMsg.setVisible(false);
                for (String string : psca)
                {
                    String val = psc.get(string);
                    ((javax.swing.DefaultListModel)lstOpt.getModel()).addElement(string+"|"+val);
                }
                freetype=false;
            }
        }
        if(stg==2)
        {
               txfManualInput.setVisible(true);
                lstOpt.setVisible(false);
                jScrollPane1.setVisible(false);
                lblMsg.setVisible(true);
                lblMsg.setText("UPID6 eingeben");
        }
        if(stg==3)
        {
            slZSC.setVisible(true);
            lblMsg.setText("Zustand auf Skala auswählen. 00 = NEuware");
            txfManualInput.setVisible(false);
        }
        if(stg==4)
        {
            clearList();
            txfManualInput.setVisible(false);
            lstOpt.setVisible(true);
            jScrollPane1.setVisible(true);
            lblMsg.setVisible(false);
            HashMap<String,String> srcsel = getSrcs();
            String[] keys = srcsel.keySet().toArray(new String[0]);
            for (String string : keys)
            {
                String val = srcsel.get(string);
                ((javax.swing.DefaultListModel)lstOpt.getModel()).addElement(string+"|"+val);
            }
        }
    }
    private void btnContinueActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnContinueActionPerformed
    {//GEN-HEADEREND:event_btnContinueActionPerformed
        
        if(stage==0)
        {
            progressOfAssist.setValue(1);
            MFID = ((String)lstOpt.getSelectedValue()).substring(0,4);

        }
        if(stage==1)
        {
            progressOfAssist.setValue(2);
            if(freetype)
            {
                PSC=txfManualInput.getText().substring(0,2);
            }
            else
            {
                PSC=((String)lstOpt.getSelectedValue()).substring(0,2);
            }
        }
        if(stage==2)
        {
            progressOfAssist.setValue(3);
            UPID6=txfManualInput.getText().substring(0,6);
        }
        
        if(stage==3)
        {
            zsc=slZSC.getValue();
            progressOfAssist.setValue(4);
        }
        if(stage==4)
        {
            src=Integer.parseInt(((String)lstOpt.getSelectedValue()).substring(0,2));
            Object[] opu = new Object[5];
            opu[0] = MFID;
            opu[1] = PSC;
            opu[2] = UPID6;
            opu[3] = zsc;
            opu[4] = src;
            PublicStorage.STO.put("upid",opu);
            PublicStorage.l.unlock();
            this.setVisible(false);
        }
        if(stage<4)
        {
            stage++;
            rebuildLST(stage);
        }
    }//GEN-LAST:event_btnContinueActionPerformed
    
    public String MFID,PSC,UPID6;//|MFID - PSC UPID6-zsc-src
    public int zsc,src,stage=0;          //|
    public boolean freetype = false;
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel.
         * For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(UPIDAssistant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(UPIDAssistant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(UPIDAssistant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(UPIDAssistant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

            public void run()
            {
                new UPIDAssistant().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnContinue;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JLabel lblMsg;
    private javax.swing.JList lstOpt;
    private javax.swing.JProgressBar progressOfAssist;
    private javax.swing.JSlider slZSC;
    private javax.swing.JTextField txfManualInput;
    // End of variables declaration//GEN-END:variables
}
