/*
 *  Table of element connections
 *
 *  2004 - 2011 Frantisek Zboril jr.
 *  Faculty of Information Technology
 *  zborilf@fit.vutbr.cz
 *  http://www.fit.vutbr.cz/~zborilf
 *
 * (C) Brno University of Technology
 * Freeware licence VUT v Brně
 * https://wis.fit.vutbr.cz/FIT/db/dir.php/dr/VZ2007/externiInformace/softwareNaWebu/Priloha2_rozh23.pdf

 */

package jTGUI;

import jTMass.TMass;
import jTMass.core.jTMassModel.TModelConnection;
import jTMass.core.jTMassModel.TModelElement;
import java.util.LinkedList;
import java.util.Vector;
import javax.swing.JTabbedPane;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;


public class TConnectionsPanel extends javax.swing.JPanel {

    TModelElement PElement;
    TMass PTMass;
    boolean PConnectionsAvailable=false;

    void updateDataPanels(){
        if(getParent()!=null)
            for(int i=0;i<((JTabbedPane)getParent()).getTabCount();i++)
                if(((JTabbedPane)getParent()).getComponentAt(i) instanceof TDataInspectionPanel)
                    ((TDataInspectionPanel)((JTabbedPane)getParent()).getComponentAt(i)).setData();
    }

    void setConnections(){

        LinkedList<TModelConnection> connections=new LinkedList<TModelConnection>();
        Vector zahlavi=new Vector();
        zahlavi.add("In/Out");
        zahlavi.add("Gate");
        zahlavi.add("Element");
        zahlavi.add("E-type");
        zahlavi.add("E-gate");
        zahlavi.add("Active value"); 
        TModelConnection con;
        int outs=0;

        try{
            if(TInOutComboBox.getSelectedIndex()!=1)
            for(int j=1; j<=PElement.getPnoOutputGates(); j++){
                con=PElement.getOutputConnection(j);

                if((con!=null))
                    if(con.getInputElement()!=null){
                        if( (TElementTypesComboBox.getSelectedIndex()==0)||
                                (con.getInputElement().getTypeName().equalsIgnoreCase
                                (TElementTypesComboBox.getSelectedItem().toString())))
                        if((TElementComboBox.getSelectedIndex()==0)||
                                (con.getInputElement().getElementName().equalsIgnoreCase
                                (TElementComboBox.getSelectedItem().toString()))){
                        connections.add(con);
                        outs++;
                    }
                }
            }

            int ins=0;

            if(TInOutComboBox.getSelectedIndex()!=2)
            for(int j=1; j<=PElement.getPnoInputGates(); j++){
                con=PElement.getInputConnection(j);
                if(con!=null){
                    if((con.getOutputElement().getTypeName().equalsIgnoreCase
                            (TElementTypesComboBox.getSelectedItem().toString()))
                        ||(TElementTypesComboBox.getSelectedIndex()==0))
                   if((con.getOutputElement().getElementName().equalsIgnoreCase
                            (TElementComboBox.getSelectedItem().toString()))
                      ||(TElementComboBox.getSelectedIndex()==0)){
                     connections.add(con);
                        ins++;
                    }
                }
            }

            TableModel newDataModel=new TMassTableModel(zahlavi,ins+outs);
            int idx=ins+outs;

            for(int i=1;i<=outs;i++){
                idx--;
                con=connections.getFirst();
                connections.removeFirst();
                newDataModel.setValueAt("OUT",idx,0);
                if(con.getInputElement()!=null){
                    newDataModel.setValueAt(con.getOutputGate(),idx,1);
                    newDataModel.setValueAt(con.getInputElement().getTypeName(),idx,3);
                    newDataModel.setValueAt(con.getInputElement().getElementName(),idx,2);
                    newDataModel.setValueAt(con.getInputGate(),idx,4);
                    newDataModel.setValueAt(con.getDataContentEx(),idx,5);
                }
            }

           for(int i=1;i<=ins;i++){
              idx--;
                con=connections.getFirst();
             connections.removeFirst();
             newDataModel.setValueAt("IN",idx,0);
             if(con.getInputElement()!=null){
                   newDataModel.setValueAt(con.getInputGate(),idx,1);
                   newDataModel.setValueAt(con.getOutputElement().getElementName(),idx,2);
                   newDataModel.setValueAt(con.getOutputElement().getTypeName(),idx,3);
                   newDataModel.setValueAt(con.getOutputGate(),idx,4);
                   newDataModel.setValueAt(con.getDataContentEx(),idx,5);
            }
         }

          TConnectionTable.setModel(newDataModel);
          TableColumn col = TConnectionTable.getColumnModel().getColumn(0);
          col.setPreferredWidth(40);
          col.setMinWidth(30);
          col.setMaxWidth(100);
          col = TConnectionTable.getColumnModel().getColumn(1);
          col.setPreferredWidth(55);
          col.setMinWidth(30);
          col.setMaxWidth(100);
          col = TConnectionTable.getColumnModel().getColumn(2);
          col.setPreferredWidth(95);
          col = TConnectionTable.getColumnModel().getColumn(3);
          col.setPreferredWidth(70);
          col = TConnectionTable.getColumnModel().getColumn(4);
          col.setPreferredWidth(55);
          col.setMinWidth(30);
          col.setMaxWidth(100);
          col = TConnectionTable.getColumnModel().getColumn(5);
          col.setPreferredWidth(160);
          updateDataPanels();
        }catch(Exception e){
            TMass._Terminal.reportError("Setting connections for "+PElement.getElementName());
        }
    }

    void setElementsCombo(String typeName){
        LinkedList typeList=new LinkedList();
        LinkedList<String> names;
        if(TElementTypesComboBox.getSelectedIndex()==0)
            typeName=null;

        typeList.add(typeName);
        names=TMass.getModel().getElementsOfTypes(typeList);
        TElementComboBox.removeAllItems();
        TElementComboBox.addItem("All Elements");
        for(String elementName:names)
           TElementComboBox.addItem(elementName);
    }

    void setComboBoxes(){
        LinkedList<String> names=TMass.getModel().getTypeNames();
        TElementTypesComboBox.removeAllItems();
        TElementTypesComboBox.addItem("All Types");
        for(String elementName:names)
           TElementTypesComboBox.addItem(elementName);
        names=TMass.getModel().getElementNames();
        TElementComboBox.removeAllItems();
        TElementComboBox.addItem("All Elements");
        for(String elementName:names)
           TElementComboBox.addItem(elementName);
    }

    // ====== CONSTRUCTOR =====

    public TConnectionsPanel(TModelElement element, TMass tmass) {
        initComponents();
        PElement=element;
        PTMass=tmass;
        setComboBoxes();
        setConnections();
        PConnectionsAvailable=true;
    }

    private TModelConnection getSelectedConnection(){
        int i=TConnectionTable.getSelectedRow();
        String inOut=TConnectionTable.getValueAt(i,0).toString();
        int gate=Integer.parseInt(TConnectionTable.getValueAt(i,1).toString());
        int j=TConnectionTable.getSelectedColumn();
        if (inOut.equalsIgnoreCase("IN"))
        return(PElement.getInputConnection(gate));
            else
                return(PElement.getOutputConnection(gate));
    }

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

        TConnectionsPopup = new javax.swing.JPopupMenu();
        TPInspectConnection = new javax.swing.JMenuItem();
        TPShowElement = new javax.swing.JMenuItem();
        TElementTypesComboBox = new javax.swing.JComboBox();
        TInOutComboBox = new javax.swing.JComboBox();
        TElementComboBox = new javax.swing.JComboBox();
        TConnectionTableScrollPane = new javax.swing.JScrollPane();
        TConnectionTable = new javax.swing.JTable();

        TConnectionsPopup.setComponentPopupMenu(TConnectionsPopup);
        TConnectionsPopup.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                onShow(evt);
            }
        });

        TPInspectConnection.setMnemonic('P');
        TPInspectConnection.setText("Incpect connection");
        TPInspectConnection.setAutoscrolls(true);
        TPInspectConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TPInspectConnectionActionPerformed(evt);
            }
        });
        TConnectionsPopup.add(TPInspectConnection);

        TPShowElement.setText("Show Element");
        TPShowElement.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TPShowElementActionPerformed(evt);
            }
        });
        TConnectionsPopup.add(TPShowElement);

        TConnectionsPopup.getAccessibleContext().setAccessibleParent(TConnectionTable);

        TElementTypesComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All Types", "Agents", "Platforms", "Environments" }));
        TElementTypesComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                TElementTypesComboBoxItemStateChanged(evt);
            }
        });
        TElementTypesComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TElementTypesComboBoxActionPerformed(evt);
                TElementTypesComboBoxtypeComboChanged(evt);
            }
        });

        TInOutComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All gates", "Input gates", "Output gates" }));
        TInOutComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                TInOutComboBoxItemStateChanged(evt);
            }
        });
        TInOutComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TInOutComboBoxActionPerformed(evt);
            }
        });

        TElementComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All Elements" }));
        TElementComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                TElementComboBoxItemStateChanged(evt);
            }
        });
        TElementComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TElementComboBoxActionPerformed(evt);
            }
        });

        TConnectionTable.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        TConnectionTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        TConnectionTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
        TConnectionTable.setComponentPopupMenu(TConnectionsPopup);
        TConnectionTableScrollPane.setViewportView(TConnectionTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TInOutComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TElementTypesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TElementComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(162, Short.MAX_VALUE))
            .addComponent(TConnectionTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TInOutComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(TElementTypesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(TElementComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TConnectionTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void TElementTypesComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TElementTypesComboBoxActionPerformed

}//GEN-LAST:event_TElementTypesComboBoxActionPerformed

    private void TElementTypesComboBoxtypeComboChanged(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TElementTypesComboBoxtypeComboChanged
        setElementsCombo((String)TElementTypesComboBox.getSelectedItem());
}//GEN-LAST:event_TElementTypesComboBoxtypeComboChanged

    private void TInOutComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TInOutComboBoxActionPerformed

}//GEN-LAST:event_TInOutComboBoxActionPerformed

    private void TElementComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TElementComboBoxActionPerformed

    }//GEN-LAST:event_TElementComboBoxActionPerformed

    private void TPInspectConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TPInspectConnectionActionPerformed
        int i=TConnectionTable.getSelectedRow();
        String inOut=TConnectionTable.getValueAt(i, 0).toString();
        TModelConnection con=this.getSelectedConnection();
        String panelName="";
        if (inOut.equalsIgnoreCase("IN"))
            panelName=panelName.concat("I");
            else
                panelName=panelName.concat("O");
        panelName=panelName.concat(TConnectionTable.getValueAt(i,1).toString());
        int found=-1;
        for(i=0;i<((JTabbedPane)getParent()).getTabCount();i++){
            if(((JTabbedPane)getParent()).getTitleAt(i).equalsIgnoreCase(panelName)){
                found=i;
                ((JTabbedPane)getParent()).setSelectedIndex(i);
            }
        }
        if(found==-1){
            this.getParent().add(new TDataInspectionPanel(con),1);
            ((JTabbedPane)this.getParent()).setSelectedIndex(1);
            ((JTabbedPane)this.getParent()).setTitleAt(1,panelName);
        }
    }//GEN-LAST:event_TPInspectConnectionActionPerformed

    private void TInOutComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_TInOutComboBoxItemStateChanged
        if(PConnectionsAvailable)
            setConnections();
    }//GEN-LAST:event_TInOutComboBoxItemStateChanged

    private void TElementComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_TElementComboBoxItemStateChanged
        if(PConnectionsAvailable)
            setConnections();
    }//GEN-LAST:event_TElementComboBoxItemStateChanged

    private void TElementTypesComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_TElementTypesComboBoxItemStateChanged
        if(PConnectionsAvailable)
            setConnections();
    }//GEN-LAST:event_TElementTypesComboBoxItemStateChanged

    private void onShow(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_onShow
        if(TConnectionTable.getSelectedColumn()>0){
        TPInspectConnection.setEnabled(true);
        TPShowElement.setEnabled(true);
        }
            else{
                TPInspectConnection.setEnabled(false);
                TPShowElement.setEnabled(false);
            }
    }//GEN-LAST:event_onShow

    private void TPShowElementActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TPShowElementActionPerformed
        TModelConnection con=this.getSelectedConnection();
        TModelElement inElement=con.getInputElement();
        TModelElement outElement=con.getOutputElement();
        if(inElement!=null)
            TMass.getPMainFrame().showElementFrame(inElement);
        if(outElement!=null)
            TMass.getPMainFrame().showElementFrame(outElement);
    }//GEN-LAST:event_TPShowElementActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable TConnectionTable;
    private javax.swing.JScrollPane TConnectionTableScrollPane;
    private javax.swing.JPopupMenu TConnectionsPopup;
    private javax.swing.JComboBox TElementComboBox;
    private javax.swing.JComboBox TElementTypesComboBox;
    private javax.swing.JComboBox TInOutComboBox;
    private javax.swing.JMenuItem TPInspectConnection;
    private javax.swing.JMenuItem TPShowElement;
    // End of variables declaration//GEN-END:variables
}
