package de.nplusc.upidgen;


import de.nplusc.izc.tools.IOtools.DBWriter;
import de.nplusc.izc.tools.baseTools.Tools;
import java.util.LinkedList;
import javax.swing.DefaultListModel;
import javax.swing.UIManager;

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

/**
 *
 * @author LH
 */
public class DependencyManager extends javax.swing.JFrame
{
            DefaultListModel lm = null,lm2 = null;;
    /**
     * Creates new form DependencyManager
     */
    public DependencyManager()
    {
                                try {
	    UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
	} catch( Exception e ) { 
	    //e.printStackTrace();
	}
        initComponents();
        lm= ((DefaultListModel)listUpidsAndDependencySet.getModel());
        lm2= ((DefaultListModel)lstAlternatives.getModel());
    }

    /**
     * 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();
        listUpidsAndDependencySet = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstAlternatives = new javax.swing.JList();
        toMainList = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jSeparator3 = new javax.swing.JSeparator();
        toMain = new javax.swing.JButton();
        refresh = new javax.swing.JButton();
        addDependency = new javax.swing.JButton();
        addalternateDep = new javax.swing.JButton();
        cxFin = new javax.swing.JCheckBox();
        cxMultiresolve = new javax.swing.JCheckBox();
        cxForceRes = new javax.swing.JCheckBox();
        jScrollPane3 = new javax.swing.JScrollPane();
        txaComm = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        listUpidsAndDependencySet.setModel(new DefaultListModel());
        listUpidsAndDependencySet.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listUpidsAndDependencySetMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listUpidsAndDependencySet);

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

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

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

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

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

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

        addDependency.setText(".add(\"Dependency\")");
        addDependency.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addDependencyActionPerformed(evt);
            }
        });

        addalternateDep.setText(".add(\"alterantive dependency\");");
        addalternateDep.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addalternateDepActionPerformed(evt);
            }
        });

        cxFin.setText("Finalized");
        cxFin.setEnabled(false);

        cxMultiresolve.setText("Mehrfacherfüllbar");
        cxMultiresolve.setEnabled(false);

        cxForceRes.setText("zwingend nötig");
        cxForceRes.setEnabled(false);

        txaComm.setColumns(20);
        txaComm.setEditable(false);
        txaComm.setRows(5);
        jScrollPane3.setViewportView(txaComm);

        jLabel1.setText("Weitere Vermerke");

        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, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(refresh)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(toMainList))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 1007, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(addDependency)
                                .addGap(29, 29, 29)
                                .addComponent(addalternateDep))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 544, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(115, 115, 115)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cxFin)
                                        .addGap(37, 37, 37)
                                        .addComponent(cxMultiresolve)
                                        .addGap(26, 26, 26)
                                        .addComponent(cxForceRes))
                                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(toMain, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(toMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(addDependency)
                    .addComponent(addalternateDep))
                .addGap(18, 18, 18)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
                            .addComponent(jSeparator2)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(74, 74, 74)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cxFin)
                            .addComponent(cxMultiresolve)
                            .addComponent(cxForceRes))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1)
                        .addGap(8, 8, 8)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(toMainList)
                    .addComponent(refresh))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    public DBWriter dbc = PublicStorage.dbc;
    private String selectedUpid = "NOP";
    boolean onTop = true;
    private void toMainActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_toMainActionPerformed
    {//GEN-HEADEREND:event_toMainActionPerformed
        Ifatzeh.sel.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_toMainActionPerformed

    private void refreshActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_refreshActionPerformed
    {//GEN-HEADEREND:event_refreshActionPerformed
        refreshList();
    }//GEN-LAST:event_refreshActionPerformed

    private void toMainListActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_toMainListActionPerformed
    {//GEN-HEADEREND:event_toMainListActionPerformed
        selectedUpid="NOP";
        onTop=true;
        refreshList();
    }//GEN-LAST:event_toMainListActionPerformed

    private void listUpidsAndDependencySetMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_listUpidsAndDependencySetMouseClicked
    {//GEN-HEADEREND:event_listUpidsAndDependencySetMouseClicked
        String load = (String)listUpidsAndDependencySet.getSelectedValue();
        if(onTop)
        {
            
            selectedUpid=load;
            refreshList();
            onTop=false;
            return;
        }
        loadDependencyDataset(load);
        updateAlternateDependencysList(load);
    }//GEN-LAST:event_listUpidsAndDependencySetMouseClicked

    private void addDependencyActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addDependencyActionPerformed
    {//GEN-HEADEREND:event_addDependencyActionPerformed
        addDependency();
    }//GEN-LAST:event_addDependencyActionPerformed

    private void addalternateDepActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addalternateDepActionPerformed
    {//GEN-HEADEREND:event_addalternateDepActionPerformed
        String src = (listUpidsAndDependencySet.getSelectedValue()+"").split("\\|")[1];
        String availDep = (listUpidsAndDependencySet.getSelectedValue()+"").split("\\|")[0];
        //String availDep = dbc.querySingleCell("Select DependencyID from DependencyLink,Dependency where Upid20='"+src+
            //    "' and DependencyLink.dependencyID = Dependency.DependencyID and Target='"+baseDep+"'");
        String gids = dbc.querySingleCell("Select ExchangeableGID from dependency where DependencyID="+availDep);
        if(gids.equals("0"))
        {
            String gname = Tools.getInputString("Gruppenname bitte");
            dbc.write("Insert into glist values(null,'"+gname+"')");
            String gid = dbc.querySIngleColumn("Select gid from glist where name='"+gname+"' ORDER BY GID desc")[0];
                                                    //hack um den gerade eingefügen bei gleichem namen zu erwischen
            //UPDATE table_name
            //SET column1=value, column2=value2,...
            //WHERE some_column=some_value
            dbc.write("Insert into dependencyExchg values(null,'"+src+"',"+gid+")");
            dbc.write("Update Dependency Set ExchangeableGID="+gid+" where DependencyID="+availDep);
            gids=gid;
            Tools.DebugHelperPrint("Init", true, "UpidTK.enableDebug");
        }
        if(gids.equals("0"))//Dbg-Code
        {
            Tools.DebugHelperPrint("FickFotze", true, "UpidTK.enableDebug");
        }
        
        
        
        
        addDependency(false,null,Integer.valueOf(gids));
        refreshList();
        updateAlternateDependencysList(availDep);

    }//GEN-LAST:event_addalternateDepActionPerformed

    private void lstAlternativesMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_lstAlternativesMouseClicked
    {//GEN-HEADEREND:event_lstAlternativesMouseClicked
        String SelectedAltUpid = ((String)lstAlternatives.getSelectedValue()).split("\\|")[1];
        //int selme = lm.lastIndexOf(SelectedAltUpid);
        String depID = dbc.querySingleCell("Select Dependency.DependencyID from DependencyLink,Dependency where Upid20='"+selectedUpid+
                "' and DependencyLink.dependencyID = Dependency.DependencyID and Target='"+SelectedAltUpid+"'");
        listUpidsAndDependencySet.setSelectedValue(depID+"|"+SelectedAltUpid, true);
        listUpidsAndDependencySetMouseClicked(evt);
    }//GEN-LAST:event_lstAlternativesMouseClicked
    public void loadDependencyDataset(String loadInf)
    {
        String[] DepIDsForTrg = dbc.querySIngleColumn("Select DependencyID from Dependency where Target='"+loadInf.substring(3)+"'");
        String[] DepIDsforSrc = dbc.querySIngleColumn("Select DependencyID from dependencyLink where UPID20='"+selectedUpid+"'");
        boolean fnd = false;
        String did = "-1";
        for (String avsrc : DepIDsforSrc)
        {
            for (String avtrg : DepIDsForTrg)
            {
                if(!fnd && avsrc.equals(avtrg))
                {
                    fnd=true;
                    did = avsrc;
                }
            }
        }
        String[] depdataSet = dbc.querySingleRow("Select * from dependency where DependencyID="+did,6);
        //Refid,DependencyID,Target,Flags,ExcahgeableGID,Comments
        
        String flagsrc = depdataSet[3].substring(2);
        String Comm = depdataSet[5];
        txaComm.setText(Comm);
        
        
        //finalized,muliresolve,forceReq;
        boolean fin = false,multiresolve=false,forceReq=false;
        if(flagsrc.substring(0,1).equals("X"))
            fin = true;
        if(flagsrc.substring(1,2).equals("X"))
            multiresolve = true;
        if(flagsrc.substring(2,3).equals("X"))
            forceReq = true;
        cxFin.setSelected(fin);
        cxMultiresolve.setSelected(multiresolve);
        cxForceRes.setSelected(forceReq);
        
    }
    
    public void refreshList()
    {
        cxFin.setSelected(false);
        cxMultiresolve.setSelected(false);
        cxForceRes.setSelected(false);
        txaComm.setText("");
        lm.clear();

        String upid=selectedUpid;
        if(upid.equals("NOP"))
        {

            String[][]availUpidsWithLink = dbc.queryTable("Select Upid20,LinkageID from upidlst where Version=2",2);
            
            
            //LinkedList<String> availUpids = new LinkedList<>();
            for (String[] Upidlin : availUpidsWithLink)
            {
                String depSet = dbc.querySingleCell("Select DependencyLink from objreg2 where LinkageID="+Upidlin[1]);
                if(depSet.equals("Enabled"))
                {
                    lm.addElement(Upidlin[0]);
                }
            }
            
            return;
        }
        try{
        String[] availDependencyIDs = dbc.querySIngleColumn("Select DependencyID from dependencyLink where UPID20='"+selectedUpid+"'");
        String[]  availDependencys = new String[availDependencyIDs.length];
        if(availDependencys.length<=0)
            return;

        for (int i = 0; i < availDependencys.length; i++)
        {
            String depid = availDependencyIDs[i];
            if(depid==null)
                {
                    Tools.DebugHelperPrint("FickFotze", true, "UpidTK.enableDebug");
                    return;
                }
            availDependencys[i] = availDependencyIDs[i]+"|"+dbc.querySingleCell("Select Target from Dependency where DependencyID="+depid);
            
        }
        for (String DID : availDependencys)
        {
            lm.addElement(DID);
            //lm.addElement(lm);<--- gibt nen fetten StackOverflow
            
        }
        }
        catch (Exception e)
        {
            Tools.DebugHelperPrint("Listfail()", true, "UpidTK.enableDebug");
        }
    }
    
    public void updateAlternateDependencysList(String depId)
    {
        lm2.clear();
        String gids = dbc.querySingleCell("Select ExchangeableGID from dependency where DependencyID="+depId.split("\\|")[0]);
        String[] upids = dbc.querySIngleColumn("Select VariantTarget from dependencyexchg where GroupID="+gids);
        for (int i = 0; i < upids.length; i++)
        {
           lm2.addElement(gids+"|"+upids[i]);
        }
    }
    public void addDependency(boolean preFilledUpid,String Upid,int gid)
    {
        String addUpid="null";
        if(!preFilledUpid)
        {
        String[] avilUpids = dbc.querySIngleColumn("Select Upid20 from Upidlst");
        addUpid = Tools.listSelectorPopup(avilUpids, "Welche Upid soll dependency sein");
        }
        else
            addUpid = Upid;
        
        
        dbc.write("Insert into DependencyLink values(null,'"+selectedUpid+"')"); 
        String currentID = dbc.querySingleCell("Select DependencyId from DependencyLink where Upid20='"+selectedUpid+"' ORDER by DependencyID DESC;");//Hack mit erstem element     
        
        LinkedList<String> Flags = new LinkedList<>();
        //this.failOut();
        boolean fin = Tools.dlg(true,"Dependency finalisieren?","Dadurch ist sie nicht mehr änderbar","Ja","Nein");
        if(fin)
            Flags.add("X");
        else
            Flags.add("D");
        boolean mult = Tools.dlg(true,"Mehrfacherfüllung möglich","","Ja","Nein");
        if(mult)
            Flags.add("X");
        else
            Flags.add("D");
        
        boolean forced = Tools.dlg(true,"Zwingend erforderlich","","Ja","Nein");
        if(forced)
            Flags.add("X");
        else
            Flags.add("D");
        String falgtrg = Flags.size()+"|";
        for (String falg : Flags)
        {
            falgtrg +=falg;
        }
        String comm = Tools.getInputString("Kommentar?", true);
        //Flags=finalized|multiResolve|forcedRequire
        dbc.write("Insert into dependency values(null,"+currentID+",'"+addUpid+"','"+falgtrg+"',"+gid+",'"+comm+"')");
        
        if(gid>0)
        {
            dbc.write("Insert into dependencyExchg values(null,'"+addUpid+"',"+gid+")");
        }

        
        
        
        
        //refID,DependencyID,Target,Flags,0(ExchangableID,wird geändert wenn benötigt,0=Default->not enab)
        
    }
    public void addDependency()
    {
        addDependency(false,null,0);
    }
    
    /**
     * @param args the command line arguments
     */
    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 DependencyManager().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addDependency;
    private javax.swing.JButton addalternateDep;
    private javax.swing.JCheckBox cxFin;
    private javax.swing.JCheckBox cxForceRes;
    private javax.swing.JCheckBox cxMultiresolve;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JList listUpidsAndDependencySet;
    private javax.swing.JList lstAlternatives;
    private javax.swing.JButton refresh;
    private javax.swing.JButton toMain;
    private javax.swing.JButton toMainList;
    private javax.swing.JTextArea txaComm;
    // End of variables declaration//GEN-END:variables
}
