package de.nplusc.upidgen;


import de.nplusc.izc.tools.baseTools.HidableTableColumnModel;
import de.nplusc.izc.tools.IOtools.DBWriter;
import de.nplusc.izc.tools.baseTools.Tools;
import de.nplusc.izc.tools.baseTools.arraytools;
import javax.management.Query;
import javax.swing.DefaultListModel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

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

/**
 *
 * @author LH
 */
public class IfatzehAR extends javax.swing.JFrame
{
    
    int selVer = 0;
    HidableTableColumnModel tm = null;
    private static DBWriter dbc = PublicStorage.dbc;
    /**
     * Creates new form IfatzehAR
     */
    public IfatzehAR()
    {
                                try {
	    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
	} catch( Exception e ) { 
	    //e.printStackTrace();
	}
        initComponents();
        tm = (HidableTableColumnModel)tblArightsInstall.getColumnModel();
        tblArightsInstall.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
        TableColumnModel m = tblArightsInstall.getColumnModel();
        for (int i = 1; i < 50; i++)
        {
            tm.setColumnVisible(i, false);
            /*TableColumn c = m.getColumn(i);
            c.setPreferredWidth(1);
            c.setHeaderValue("");
           // c.setWidth(0);
            //c.setMaxWidth(0);*/
        }
        refreshUpids();
    }
    public void killColumnsFrom(int idx)
    {
        cols=idx;
        for (int i = idx; i < 50; i++)
        {
            tm.setColumnVisible(i, false);
        }
    }
    int cols = 1;
    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)tblArightsInstall.getModel();
        m.setValueAt(val, row, col);
    }
    
    
    int rows=0;
    public void insertRow()
    {
        rows++;
        Tools.DebugHelperPrint("AddRow", true, "UpidTK.enableDebug");
       ((DefaultTableModel)tblArightsInstall.getModel()).addRow(new String[50]);//nötig da unsivtbare ZEllen auch vorhanden sonst npx!!!!!!!!
       ((DefaultTableModel)tblArightsInstall.getModel()).setRowCount(rows);
    }
    public void removeRow()
    {
        rows--;
        Tools.DebugHelperPrint("RMVRow", true, "UpidTK.enableDebug");
       ((DefaultTableModel)tblArightsInstall.getModel()).removeRow(rows);//nötig da unsivtbare ZEllen auch vorhanden sonst npx!!!!!!!!
       ((DefaultTableModel)tblArightsInstall.getModel()).setRowCount(rows);
    }
    /**
     * 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();
        tblArightsInstall = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        LSTUPids = new javax.swing.JList();
        refreshUPIDS = new javax.swing.JButton();
        btnAddDataset = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        breturn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tblArightsInstall.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "TargetUserID", "Title 2", "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"
            }
        ) {
            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 boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblArightsInstall.setColumnModel(new HidableTableColumnModel(tblArightsInstall.getColumnModel()));
        tblArightsInstall.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblArightsInstallMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblArightsInstall);

        LSTUPids.setModel(new DefaultListModel());
        LSTUPids.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LSTUPidsMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(LSTUPids);

        refreshUPIDS.setText("Refresh");
        refreshUPIDS.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshUPIDSActionPerformed(evt);
            }
        });

        btnAddDataset.setText("Add Rights-Dataset");
        btnAddDataset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddDatasetActionPerformed(evt);
            }
        });

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

        breturn.setText("Back to Main");
        breturn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                breturnActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(refreshUPIDS)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 519, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(btnAddDataset)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(breturn, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(26, 26, 26))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(refreshUPIDS)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 447, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 461, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(breturn)))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btnAddDataset))
        );

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

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

        refreshUpids();
    }//GEN-LAST:event_refreshUPIDSActionPerformed

    public void refreshUpids()
    {
                        ((DefaultListModel)(LSTUPids.getModel())).clear();
        String[] availUPIDs = dbc.querySIngleColumn("Select UPID20 from upidlst");
        
        for (String elem : availUPIDs)
        {
            ((DefaultListModel)(LSTUPids.getModel())).addElement(elem);
        }
    }
    String selLinkID = "0";
    private void LSTUPidsMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_LSTUPidsMouseClicked
    {//GEN-HEADEREND:event_LSTUPidsMouseClicked
        String upid = (String)LSTUPids.getSelectedValue();
        
        String arightLnkID = dbc.querySingleCell("select RightsLinkageID from ArightsLink where TargetUPID='"+upid+"'");
        selLinkID = arightLnkID;
        int version = 0;
        if(arightLnkID==null)
        {
            boolean NT = Tools.dlg(true, "Uninitialisierter Datensahtz", "Version wählen", "Version 2", "Version 1");
            
            version=1;
            
            if(NT)version=2;
            initializeUPIDDataset(upid, version);
            
        }
        else
        {
            version=Integer.valueOf(dbc.querySingleCell("select Version from ArightsLink where rightsLinkageID="+arightLnkID));
        }
        selVer = version;
        refreshTable(upid, version);
    }//GEN-LAST:event_LSTUPidsMouseClicked

    private void btnAddDatasetActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnAddDatasetActionPerformed
    {//GEN-HEADEREND:event_btnAddDatasetActionPerformed
        String UUID="",Src="",upid = (String)LSTUPids.getSelectedValue(),query = "";
        String RightLinkageID = dbc.querySingleCell("select RightsLinkageID from ArightsLink where TargetUPID='"+upid+"'");
        if(selVer==1)
        {
            String CSUM;
            UUID = Tools.getInputString(" UUID in alter Syntax");
            Src = Tools.getInputString(" Ausstellercode in alter Syntax");
            CSUM = Tools.getInputString("CSUM");
            
            //rightLinkageID,Source,Target,Version(1),InternalID(leave null),CSUM
            query = "Insert into Arights1 values("+RightLinkageID+",'"+Src+"','"+UUID+"',1,null,'"+CSUM+"')";
            
        }
        if(selVer==2)
        {
            String[][] availUUIDSraw = dbc.queryTable("Select * from User",2);
            String[] availUUIDs = new String[availUUIDSraw.length];
            for (int i = 0; i < availUUIDSraw.length; i++)
            {
                availUUIDs[i] = availUUIDSraw[i][0]+"|"+availUUIDSraw[i][1];
            }
            
            UUID = Tools.listSelectorPopup(availUUIDs, "Wähle die gewünschte UUID für den der Datensatz gilt").split("\\|")[0];
            Src = Tools.listSelectorPopup(availUUIDs, "Wähle die gewünschte UUID für den Ersteller").split("\\|")[0];
            query = "Insert into Arights2 values("+RightLinkageID+","+Src+","+UUID+",2,'"+catSelK+"',null)";
        }
        dbc.write(query);
        refreshTable(upid, selVer);
    }//GEN-LAST:event_btnAddDatasetActionPerformed
    
    String[] availFlagVals = new String[]{"E","V","W","N"};
    
    private void tblArightsInstallMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_tblArightsInstallMouseClicked
    {//GEN-HEADEREND:event_tblArightsInstallMouseClicked
        String upid = (String)LSTUPids.getSelectedValue();
        int x = tblArightsInstall.getSelectedColumn(); 
        int y = tblArightsInstall.getSelectedRow();
        if(x==0)
        {
            return;
        }
        String selFlag = hdr[x-1];
        Tools.DebugHelperPrint(selFlag, true, "UpidTK.enableDebug");
        if(evt.getClickCount()==2)
        {
            String DatasetID = "",USERID = "";
            String FlagID = dbc.querySingleCell("Select Flag_Key from flag_descriptor where FlagName='"+selFlag+"'");
            Tools.DebugHelperPrint(FlagID+"|"+selFlag, true, "UpidTK.enableDebug");
            String FlagVal = Tools.listSelectorPopup(availFlagVals, "Welcher Wert???");
            if(selVer==1)
            {
                USERID = (String)tblArightsInstall.getValueAt(y, 0);
                DatasetID = dbc.querySingleCell("Select InternalID from Arights1 where Target='"+USERID+"'and RightsLinkageID="+selLinkID);
            }
            if(selVer==2)
            {
                USERID = ((String)tblArightsInstall.getValueAt(y, 0)).split("\\|")[0];
                Tools.DebugHelperPrint(USERID+"|UserID", true, "UpidTK.enableDebug");
                DatasetID = dbc.querySingleCell("Select ID from Arights2 where target="+USERID+" and RightsLinkageID="+selLinkID);
            }
            
                //UPDATE table_name
                //SET column1=value, column2=value2,...
                //WHERE some_column=some_value
            //DatasetID = dbc.querySingleCell("Select InternalID from Arights1 where Target='"+USERID+"'and RightsLinkageID="+selLinkID);
            try
            {
            dbc.write("Update arightsflag Set value='"+FlagVal+"' where FlagKey ="+FlagID+" and Version ="+selVer+" and DatasetID="+DatasetID,true,true);    
                
            }
            catch (Exception e)
            {
                dbc.write("Insert into Arightsflag values(null,"+FlagID+",'"+FlagVal+"',"+DatasetID+","+selVer+")");
                //dbc.write("Insert into")
            }
            refreshTable(upid,selVer);
            
            
        }
    }//GEN-LAST:event_tblArightsInstallMouseClicked

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

    /**
     * @param args the command line arguments
     */
    
    
    
    
    public void initializeUPIDDataset(String upid, int Version)
    {
        dbc.write("Insert into ArightsLink values(null,'"+upid+"',"+Version+")");
        LSTUPidsMouseClicked(null);
    }
    
    String[] hdr = null;
    boolean firstrun = true;
    public void refreshTable(String UPID,int version)
    {
        if(firstrun)
        {
            insertRow();
            firstrun=false;
        }
        while(rows>1)
        {
            removeRow();
        }
        for (int i = 0; i < 50; i++)
        {
            for (int j = 0; j < rows; j++)
            {
                insertValueToTable("", j, i);
            }
            
        }
        
        killColumnsFrom(1);
        
        
        
        
        if(version==1) hdr = dbc.querySIngleColumn("Select FlagName from Flag_descriptor ORDER BY Flag_Key Asc");
        else hdr = getAvailFlags(UPID);
        for (String hdre : hdr)
        {
            insertColumn(hdre);
        }
        
        String[][] table = null;
        String LinkageID = dbc.querySingleCell("Select RightsLinkageID from Arightslink where TargetUPID='"+UPID+"'");
        int i=0;
        if(version==1)
        {
            table = dbc.queryTable("Select * from Arights1 where RightsLinkageID="+LinkageID, 6);
            
            for (String[] rowcnt : table)
            {
                if(i>=1)
                {
                    insertRow();
                }
                //String cplUUID = rowcnt[3]+"|"+dbc.querySingleCell("Select Name from User where UserID="+rowcnt[3]);
                insertValueToTable(rowcnt[2], i, 0);
                
                String[][] SetFlags = dbc.queryTable("Select FlagKey,Value from arightsflag where Version=1 and DatasetID="+rowcnt[4], 2);
                for (String[] aFlag : SetFlags)
                {
                    String flagVal = dbc.querySingleCell("Select Flagname from Flag_descriptor where Flag_Key="+aFlag[0]);
                    int tablepos = arraytools.getElemPosInArray(hdr, flagVal)+1;
                    Tools.DebugHelperPrint(tablepos+"", true, "UpidTK.enableDebug");
                    insertValueToTable(aFlag[1], i, tablepos);
                }
                i++;
            }
        }
        if(version==2)
        {
            table = dbc.queryTable("Select * from Arights2 where RightsLinkageID="+LinkageID, 6);
            for (String[] rowcnt:table)
            {
                if(i==rows)
                {
                    insertRow();
                }
                String cplUUID = rowcnt[2]+"|"+dbc.querySingleCell("Select Name from User where UserID="+rowcnt[2]);
                
                insertValueToTable(cplUUID, i, 0);
                
                String[][] SetFlags = dbc.queryTable("Select FlagKey,Value from arightsflag where Version=2 and DatasetID="+rowcnt[5], 2);
                for (String[] aFlag : SetFlags)
                {
                    String flagVal = dbc.querySingleCell("Select Flagname from Flag_descriptor where Flag_Key="+aFlag[0]);
                    int tablepos = arraytools.getElemPosInArray(hdr, flagVal)+1;
                    Tools.DebugHelperPrint(tablepos+"", true, "UpidTK.enableDebug");
                    insertValueToTable(aFlag[1], i, tablepos);
                }
                i++;
            }
        }
        
        
    }
    
    String catSelK;
    public String[] getAvailFlags(String UPID20)
    {
        String t1c = UPID20.substring(0,4);
        String t2c = UPID20.substring(0,2);
        catSelK = t1c;
        String CatIDT1 = dbc.querySingleCell("Select CategoryID from category where CategoryName='"+t1c+"'");
        String CatIDT2 = dbc.querySingleCell("Select CategoryID from category where CategoryName='"+t2c+"'");
        if(CatIDT1==null)
        {
            catSelK = t2c;
            CatIDT1=CatIDT2;
        }
        String[] availFlagIDs = dbc.querySIngleColumn("Select FlagKey from flagcat where CatID="+CatIDT1+" ORDER BY FlagKey ASC");
        
        String[] FlagNames = new String[availFlagIDs.length];
        for (int i = 0; i < FlagNames.length; i++)
        {
           FlagNames[i] = dbc.querySingleCell("Select FlagName from Flag_descriptor where Flag_key="+availFlagIDs[i]);
           
        }
        
        return FlagNames;
    }
    
    public static void main(String args[])
    {
                        try {
	    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
	} catch( Exception e ) { 
	    //e.printStackTrace();
	}
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable()
        {

            public void run()
            {
                new IfatzehAR().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList LSTUPids;
    private javax.swing.JButton breturn;
    private javax.swing.JButton btnAddDataset;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton refreshUPIDS;
    private javax.swing.JTable tblArightsInstall;
    // End of variables declaration//GEN-END:variables
}
