package de.nplusc.upidgen;


import de.nplusc.izc.tools.IOtools.DBWriter;
import de.nplusc.izc.tools.baseTools.HidableTableColumnModel;
import de.nplusc.izc.tools.baseTools.Tools;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

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

/**
 *
 * @author LH
 */
public class ArightsCatEditor extends javax.swing.JFrame
{

    /**
     * Creates new form ArightsCatEditor
     */
    HidableTableColumnModel tm = null;
    private static DBWriter dbc = PublicStorage.dbc;
    public ArightsCatEditor()
    {
                                try {
	    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
	} catch( Exception e ) { 
	    //e.printStackTrace();
	}
        initComponents();
        
        tm = (HidableTableColumnModel)tblCategmatrix.getColumnModel();
        tblCategmatrix.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
        //TableColumnModel m = tblCategmatrix.getColumnModel();
        for (int i = 2; i < 50; i++)
        {
            tm.setColumnVisible(i, false);
            /*TableColumn c = m.getColumn(i);
            c.setPreferredWidth(1);
            c.setHeaderValue("");
           // c.setWidth(0);
            //c.setMaxWidth(0);*/
            
        }
        
        /*
        insertColumn("Test");
        insertColumn("Test2");
        
        insertColumn("Test3");
        insertColumn("Test4");
        insertRow();
        insertRow();*/
        
    }

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

        jScrollPane1 = new javax.swing.JScrollPane();
        tblCategmatrix = new javax.swing.JTable();
        fetch = new javax.swing.JButton();
        flagSwitch = new javax.swing.JToggleButton();
        btnRet = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        DefaultTableModel m = new javax.swing.table.DefaultTableModel(
            new Object [2][50],
            new String [] {
                "KEy descrip", "Key", "","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        };
        TableColumnModel m2 =new DefaultTableColumnModel();
        for(int i=0;i<50;i++)
        {
            int w = 200;
            if(i>1) w = 30;
            m2.addColumn(new TableColumn(i,w));
        }
        tblCategmatrix.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Description", "Key", "Title 3", "Title 4", "Title 5", "Title 6", "Title 7", "Title 8", "Title 9", "Title 10", "Title 11", "Title 12", "Title 13", "Title 14", "Title 15", "Title 16", "Title 17", "Title 18", "Title 19", "Title 20", "Title 21", "Title 22", "Title 23", "Title 24", "Title 25", "Title 26", "Title 27", "Title 28", "Title 29", "Title 30", "Title 31", "Title 32", "Title 33", "Title 34", "Title 35", "Title 36", "Title 37", "Title 38", "Title 39", "Title 40", "Title 41", "Title 42", "Title 43", "Title 44", "Title 45", "Title 46", "Title 47", "Title 48", "Title 49", "Title 50"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblCategmatrix.setColumnModel(new HidableTableColumnModel(tblCategmatrix.getColumnModel()));
        tblCategmatrix.getTableHeader().setReorderingAllowed(false);
        tblCategmatrix.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblCategmatrixMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblCategmatrix);

        fetch.setText(".fetch()");
        fetch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fetchActionPerformed(evt);
            }
        });

        flagSwitch.setText("Flag State:Disabled");
        flagSwitch.setEnabled(false);
        flagSwitch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                flagSwitchActionPerformed(evt);
            }
        });

        btnRet.setText("Back to Select");
        btnRet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRetActionPerformed(evt);
            }
        });

        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(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 950, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(fetch, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(167, 167, 167)
                        .addComponent(flagSwitch)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnRet)
                        .addGap(55, 55, 55))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fetch)
                    .addComponent(flagSwitch)
                    .addComponent(btnRet))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

    private void fetchActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_fetchActionPerformed
    {//GEN-HEADEREND:event_fetchActionPerformed
        fetch();
    }//GEN-LAST:event_fetchActionPerformed

    
    private void tblCategmatrixMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_tblCategmatrixMouseClicked
    {//GEN-HEADEREND:event_tblCategmatrixMouseClicked
        int y = tblCategmatrix.getSelectedColumn();
        int x = tblCategmatrix.getSelectedRow();
        boolean sel = false;
        try{
        if(tblCategmatrix.getModel().getValueAt(x, y).equals("X"))
        {
            flagSwitch.setSelected(true);
            flagSwitch.setText("Flag State:Enabled");
            sel=true;
        }
        else throw new Exception();
        }
        catch(Exception e)
        {
            flagSwitch.setSelected(false);
            flagSwitch.setText("Flag State:Disabled");
        }
        if(evt.getClickCount()==2)
        toggleFlag(sel);
    }//GEN-LAST:event_tblCategmatrixMouseClicked

    private void flagSwitchActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_flagSwitchActionPerformed
    {//GEN-HEADEREND:event_flagSwitchActionPerformed

    }//GEN-LAST:event_flagSwitchActionPerformed

    private void btnRetActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnRetActionPerformed
    {//GEN-HEADEREND:event_btnRetActionPerformed
        Ifatzeh.sel.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_btnRetActionPerformed

    public void toggleFlag(boolean sel)
    {
        int y = tblCategmatrix.getSelectedColumn()-1;//2 nch links udn das Offset des Indexes in DB
        int x = tblCategmatrix.getSelectedRow()+1; //Offset des idxes in DB
        if(flagSwitch.isSelected()) 
            disableFlag(x,y);
        else
            enableFlag(x,y);
        
        fetch();
    }
    
    
    public void enableFlag(int flagKey,int catKey)
    {
         dbc.write("Insert into FlagCat values(null,"+flagKey+","+catKey+")");
    }
    public void disableFlag(int flagKey,int catKey)
    {
        dbc.write("DELETE FROM `upidtk`.`flagcat` WHERE FlagKey="+flagKey+" AND CatID = "+catKey);
    }
    
    boolean firstrun = true;
    public void fetch()
    {
        for (int i = 0; i < 50; i++)
        {
            for (int j = 0; j < rows; j++)
            {
                insertValueToTable("",j,i);
                
            }
            
        }
        if(firstrun)
        {
        insertRow();
        insertRow();
        firstrun=false;
        }
        String[][] FlagDefine = dbc.queryTable("Select * from flag_descriptor ORder by Flag_key",3);
        String[][] CatDefine = dbc.queryTable("Select * from category",2);
        String[][] Linkage = dbc.queryTable("Select * from flagcat",3);
        for(int i=0;i<FlagDefine.length;i++)//FlagListe erzeuchen
        {

            insertValueToTable(FlagDefine[i][2],i,0);
            insertValueToTable(FlagDefine[i][1],i,1);
            if(i+1>=rows&&i+1<FlagDefine.length)
            {
                insertRow();
            }
        }
        killColumnsFrom(2);
        for (int i = 0; i < CatDefine.length; i++)
        {
                insertColumn(CatDefine[i][1]);
        }
        for (int i = 0; i < Linkage.length; i++)
        {
            String[] link = Linkage[i];
            Tools.DebugHelperPrint(link[0]+"|"+link[1]+"|"+link[2], true, "UpidTK.enableDebug");
            insertValueToTable("X",Integer.valueOf(link[1])-1,Integer.valueOf(link[2])+1);
            
        }
    }
    
    public void killColumnsFrom(int idx)
    {
        cols=idx;
        for (int i = idx; i < 50; i++)
        {
            tm.setColumnVisible(i, false);
        }
    }
    int cols = 2;
    public void insertColumn(String tit)
    {
        tm.setColumnVisible(cols, true);
        
        tm.getColumn(cols).setHeaderValue(tit);
                cols++;
        Tools.DebugHelperPrint("AddCol", true, "UpidTK.enableDebug");
        
        // HACkmit unsichtbaren Reservesalten :-)
        
       //TableColumn column = new TableColumn();
    
    }
    
    public void insertValueToTable(String val,int row,int col)
    {
        DefaultTableModel m = (DefaultTableModel)tblCategmatrix.getModel();
        m.setValueAt(val, row, col);
    }
    
    
    int rows=0;
    public void insertRow()
    {
        rows++;
        Tools.DebugHelperPrint("AddRow", true, "UpidTK.enableDebug");
       ((DefaultTableModel)tblCategmatrix.getModel()).addRow(new String[50]);//nötig da unsivtbare ZEllen auch vorhanden sonst npx!!!!!!!!
       ((DefaultTableModel)tblCategmatrix.getModel()).setRowCount(rows);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
        try 
        {
	    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
	} catch( Exception ignored) 
        { 
	    //e.printStackTrace();
	}
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable()
        {

            @Override
            public void run()
            {
                new ArightsCatEditor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRet;
    private javax.swing.JButton fetch;
    private javax.swing.JToggleButton flagSwitch;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblCategmatrix;
    // End of variables declaration//GEN-END:variables
}
