/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
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.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

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

    /**
     * Creates new form ArightsFlagDependencys
     */
    public ArightsFlagDependencys()
    {
        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);

        }
    }
    HidableTableColumnModel tm = null;
    private static DBWriter dbc = PublicStorage.dbc;

    /**
     * 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")
    
    private static String[] availFlagVals = new String [] {"(Remove)","Depending","Not allowed with this"};
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblcategmatrix = new javax.swing.JTable();
        btnRetToMain = new javax.swing.JButton();
        jButton1 = 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 [][]
            {
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null}
            },
            new String []
            {
                "\\/This depends", "on this>>", "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.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.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);
        tblcategmatrix.getColumnModel().getColumn(0).setResizable(false);
        tblcategmatrix.getColumnModel().getColumn(1).setResizable(false);
        tblcategmatrix.getColumnModel().getColumn(2).setResizable(false);
        tblcategmatrix.getColumnModel().getColumn(3).setResizable(false);
        tblcategmatrix.getColumnModel().getColumn(4).setResizable(false);
        tblcategmatrix.getColumnModel().getColumn(5).setResizable(false);
        tblcategmatrix.getColumnModel().getColumn(6).setResizable(false);
        tblcategmatrix.getColumnModel().getColumn(7).setResizable(false);

        btnRetToMain.setText("Return to Menu");
        btnRetToMain.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                btnRetToMainActionPerformed(evt);
            }
        });

        jButton1.setText("Fetch data");
        jButton1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 826, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnRetToMain, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnRetToMain)
                        .addGap(65, 65, 65)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void changeFlag(int x,int y)
    {
        String FlagVal = Tools.listSelectorPopup(availFlagVals, "Status");
        DefaultTableModel m = (DefaultTableModel) tblcategmatrix.getModel();
        String flagName1=m.getValueAt(x, 1)+"";
        int flagID1 = Integer.valueOf(dbc.querySingleCell("Select Flag_Key from flag_descriptor where FlagName='"+flagName1+"'"));
        String flagName2 = tm.getColumn(y).getHeaderValue()+"";
        int flagID2 = Integer.valueOf(dbc.querySingleCell("Select Flag_Key from flag_descriptor where FlagName='"+flagName2+"'"));
                Tools.DebugHelperPrint(flagName1+"|flagname1|"+flagName2+"|flagname2", true, "UpidTK.enableDebug");
        if(FlagVal.equals(availFlagVals[0]))
        {
            dbc.write("DELETE FROM flagdep WHERE flag="+flagID1+" AND depflag = "+flagID2);
        }
        String updootQuery = "";
        boolean ColumnIsFilled = !((m.getValueAt(x, y)+"").equals(""));
        if(FlagVal.equals(availFlagVals[1]))
        {
            if(ColumnIsFilled)
            {
                updootQuery="UPDATE flagdep " +
                "SET inverted=0" +
                "WHERE flag="+flagID1+" AND depflag="+flagID2;
            }
            else
            {
                updootQuery = "Insert into flagdep values(NULL,"+flagID1+","+flagID2+",+0)";
            }
        }
        if(FlagVal.equals(availFlagVals[2]))
        {
            if(ColumnIsFilled)
            {
                                updootQuery="UPDATE flagdep " +
                "SET inverted=1 " +
                "WHERE flag="+flagID1+" AND depflag = "+flagID2;
            }
            else
            {
                updootQuery = "Insert into flagdep values(NULL,"+flagID1+","+flagID2+",+1)";
            }
        }
        if(!updootQuery.equals(""))
            dbc.write(updootQuery);
        fetch();
    }
    
    
    
    
    
    private void btnRetToMainActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnRetToMainActionPerformed
    {//GEN-HEADEREND:event_btnRetToMainActionPerformed
        Ifatzeh.sel.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_btnRetToMainActionPerformed

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

    private void tblcategmatrixMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_tblcategmatrixMouseClicked
    {//GEN-HEADEREND:event_tblcategmatrixMouseClicked
        int y = tblcategmatrix.getSelectedColumn();
        int x = tblcategmatrix.getSelectedRow();
        if(evt.getClickCount()==2&&y>1)
        changeFlag(x,y);
    }//GEN-LAST:event_tblcategmatrixMouseClicked

    /**
     * @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(ArightsFlagDependencys.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(ArightsFlagDependencys.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(ArightsFlagDependencys.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(ArightsFlagDependencys.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 ArightsFlagDependencys().setVisible(true);
            }
        });
    }
    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[][] Linkage = dbc.queryTable("Select * from flagdep", 3);
        killColumnsFrom(2);
        for (int i = 0; i < FlagDefine.length; i++)//FlagListe erzeuchen
        {

            insertValueToTable(FlagDefine[i][2], i, 0);
            insertValueToTable(FlagDefine[i][1], i, 1);
            insertColumn(FlagDefine[i][1]);
            if (i + 1 >= rows && i + 1 < FlagDefine.length)
            {
                insertRow();
            }
        }

      //  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);

        }*/
        String[][] definitions = dbc.queryTable("Select flag , depflag , inverted from flagdep", 3);
        for (String[] row : definitions)
        {
            String RowString = availFlagVals[1];
            if(!(row[2].equals("0")))
            {
                RowString =  availFlagVals[2];
            }
            insertValueToTable(RowString,Integer.valueOf(row[0])-1, Integer.valueOf(row[1])+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);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRetToMain;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblcategmatrix;
    // End of variables declaration//GEN-END:variables
}
