package eu.artemis.shield.overlay.securityagent.impl;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

import javax.swing.*;

import javax.swing.table.*;

import java.net.URL; 

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;

import eu.artemis.shield.composition.compositionmanager.ICompositionManager;
import eu.artemis.shield.overlay.securityagent.impl.SA;


public class SAGUI extends Frame implements ActionListener 
{
  private static final long serialVersionUID = 82484L;
                      //   UAGUI

  private static final int MAJOR = 1;
  private static final int MINOR = 0;
  
  private static final int width = 440;
  private static final int height = 440;
  
  private BundleContext bc = null;  
  private SA sa = null;
  private HashMap ht = null;
  
  private ICompositionManager cm = null;
  
  private Vector types_vector = null;
  private Vector services_discovered = null;
  
  private JComboBox cb = null;
  
  private JScrollPane  table_panel = null;
  private JPanel services_panel = null;
  private JPanel combo_panel = null;
  private JPanel buttons_panel = null;
  private JTable services_table = null;
  
  private DefaultTableModel table_model = null;
  
  private Vector columnNames = null;
  
  private static final int intNumBtn = 3
  private static String[] strBtn = new String[intNumBtn];
  
  // -----------------------------------------------
  //  CONSTRUCTORS
  // -----------------------------------------------    
  
  public SAGUI(BundleContext bc, SA sa)
    {    
      super("pSHIELD - Security Agent MOD v" + MAJOR + "." + MINOR);
      
      strBtn[0"Types Discovery";  
      strBtn[1"Services Discovery";
      strBtn[2"Hide Me";
      
      columnNames = new Vector();
      
      columnNames.add("Icon");
      columnNames.add("Name");
      columnNames.add("Run");
      
      this.bc = bc;
      this.sa = sa;
      
      addWindowListener(windowExit);
      
      createGUI();
        
      setSize(width,height);
        setForeground(Color.black);
        setBackground(Color.lightGray);
        
        /*
         * ENABLE / DISABLE THE GUI...
         */
        
    // this.pack();
    setVisible(true);
    }
  
  //  -----------------------------------------------
  //  EVENT HANDLER
  // -----------------------------------------------
    
    WindowAdapter windowExit = new WindowAdapter()
  {
      public void windowClosing(WindowEvent e
      
        actionExit();
        }
    };
    
    public void actionExit() 
    {       
        // Exiting...
      if (bc != null)
      {
        try 
        {
          bc.getBundle().stop();   
        }        
        catch (BundleException BE)
        {
          BE.printStackTrace();
        }
      }      
  }
    
    public void actionPerformed(ActionEvent e
    {            
      if (e.getActionCommand().equals(strBtn[0]))
    {  
        try{
          int i = 0;
              types_vector = sa.serviceTypeDiscovery();
              cb.removeAllItems();
              if sa != null ){
            
            Iterator it = types_vector.iterator();
            
            while it.hasNext() ){
              cb.insertItemAt( (Stringit.next(), i );
              i++;
            }
              }
        }catch (Exception ex){
          ex.printStackTrace();
        }
        
        cb.setEditable(false);
        cb.setEnabled(true);
        
    }
    else if (e.getActionCommand().equals(strBtn[1]))
    {  
      String type_selected = (Stringcb.getSelectedItem();
      if type_selected != null ) {
        
        try {
          services_discovered = sa.serviceDiscoverytype_selected );
        catch (Exception e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }
        
      }
      else JOptionPane.showMessageDialognull "Select a Service Type" );
      
      List l = sa.getServices(11);
      ht = sa.getParameters(l);
            
      // Initialize the services table with the services discovered
      initializeServicesTableservices_discovered )
      
    }
    else if (e.getActionCommand().equals(strBtn[2]))
    {
      setVisible(false);
    }
    else
    {
      //Unknown Command
    }    
    }
    
    /**
     * Function that initialize and the services table with a data vector
     @param data the data vector ( if it is null, the table will be empty )
     */
    private void initializeServicesTableVector data ){
      
      table_model = new DefaultTableModel();
    table_model.addColumn("Name");
    table_model.addColumn("Description");
    table_model.addColumn("");
      
    if data != null && !data.isEmpty() ){
      
      Iterator it = data.iterator();
        
        while it.hasNext() ){
          
          Hashtable ht = Hashtable it.next();
          
          if ht.containsKey"Service Name" && ht.containsKey"Service Description" ) ) {
          
          String serv_name = (String)((Vector)ht.get("Service Name")).elementAt(0);
          String description = (String)((Vector)ht.get("Service Description")).elementAt(0);
          
          if serv_name != null && description != null )  {
            table_model.addRownew Object[] { serv_name, description, "Run"} );
          }
          
          }
        }
    }
    
    services_table = new JTable table_model ){
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int column)
            {  
              if getValueAt(0, column== null )
                return null;
              else 
                return getValueAt(0, column).getClass();
            }
            public boolean isCellEditable(int row, int col) {
                if col == )
                  return true;
                else 
                  return false;
            }
            
            public String getToolTipText(MouseEvent e) {
                String tip = null;
                java.awt.Point p = e.getPoint();
                int rowIndex = rowAtPoint(p);
                int colIndex = columnAtPoint(p);
                int realColumnIndex = convertColumnIndexToModel(colIndex);
                
                if services_discovered != null ){
                  
                  Hashtable tmp = (Hashtableservices_discovered.elementAtrowIndex );
                  String description = String ) ( ( Vector tmp.get"Service Description" ) ).elementAt(0);
                  
                  if realColumnIndex < ) {
                    tip = description;
                  }
                }
                
                return tip;
            
            }

        };
        
        //  Create the button column
        ButtonColumn buttonColumn = new ButtonColumn(services_table, 2);
        
        services_table.setPreferredScrollableViewportSize(new Dimension(50070));
    services_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    services_table.setColumnSelectionAllowed(false);
    services_table.setRowSelectionAllowed(true);

    table_panel = new JScrollPaneservices_table );
    
    services_panel.removeAll();
    
    services_panel.addcombo_panel, BorderLayout.PAGE_START );
    services_panel.addtable_panel, BorderLayout.CENTER );
      services_panel.addbuttons_panel, BorderLayout.PAGE_END );
    
    services_panel.validate();
    
    }
    
    // -----------------------------------------------
  //  DESIGN GRAPHICS
  // -----------------------------------------------
    
    private void createGUI()
    {  
      
      // Initialize the main Panel
    services_panel = new JPanel ( );
    services_panel.setLayoutnew BorderLayout() );
    services_panel.setBorderBorderFactory.createCompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()) );
    
    // Initialize the Combo Panel
    combo_panel = new JPanel();
    
    GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        
    combo_panel.setLayoutgridbag );
    
    c.gridwidth = 1;   // The cell occupies 1 column 
        c.gridheight = 1;  // The cell occupies 1 row
      c.gridx = 0;    // The cell is located in 1 column 
        c.gridy = 0;    // The cell is located in 1 row    
        c.weightx = 0.0;  // The cell occupies the minimum row length
    c.weighty = 0.1;  // The cell occupies the entire column length
    
      JLabel lab = new JLabel("Choose a Service Type :");
        gridbag.setConstraintslab, c);
        combo_panel.add(lab);

        types_vector = new Vector();
    
        cb = new JComboBoxtypes_vector );
        
    cb.setEditable(false);
    cb.setEnabled(true);

    c.gridwidth = 3;   // The cell occupies 1 column 
        c.gridheight = 1;  // The cell occupies 1 row
      c.gridx = 1;    // The cell is located in 1 column 
        c.gridy = 0;    // The cell is located in 1 row    
        c.weightx = 0.1;  // The cell occupies the entire row length
    c.weighty = 0.1;  // The cell occupies the entire column length

    gridbag.setConstraintscb, c);
        combo_panel.add(cb);
    
    // Initialize the Buttons Panel
    buttons_panel = new JPanel();
    
    for (int i = 0; i < intNumBtn; i++)
      {
        /*
           * ADD BUTTONS TO START SEVERAL TEST
           */     
          Button b = new Button(strBtn[i]);
            //gridbag.setConstraints(b, c);
            b.addActionListener(this);
            buttons_panel.add(b);
      
    
    // Create an empty table
    initializeServicesTablenull );
    
    // Add the subpanels to the main panel 
    services_panel.addcombo_panel, BorderLayout.PAGE_START );
    
    services_panel.addtable_panel, BorderLayout.CENTER );
    
    services_panel.addbuttons_panel, BorderLayout.PAGE_END );
      
    // Add the main panel to the Frame
    addservices_panel );
      
      /*
         * CENTER FRAME ON THE SCREEN
         */
        Dimension dialogSize = getSize();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation(screenSize.width/- dialogSize.width/2, screenSize.height/- dialogSize.height/2);
        
        /*
         * pSHIELD ICON 
         */
        try
      {  
          /*
           * Check if we are in a JAR file...
           */
          URL url = this.getClass().getResource("logo_pSHIELD_16x16.jpg");
          if (url != null)
          {
            this.setIconImage(Toolkit.getDefaultToolkit().createImage(url));  
          }                      
          else
          {
            /*
               * We are not in a JAR file...
               */                           
          }
      }
        catch(Exception e)
        {  
          e.printStackTrace();
        
    }
    
    class ButtonColumn extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener {
      JTable table;
      JButton renderButton;
      JButton editButton;
      String text;
  
      public ButtonColumn(JTable table, int column) {
          super();
          this.table = table;
          renderButton = new JButton();
  
          editButton = new JButton();
          editButton.setFocusPaintedfalse );
          editButton.addActionListenerthis );
  
          TableColumnModel columnModel = table.getColumnModel();
          columnModel.getColumn(column).setCellRendererthis );
          columnModel.getColumn(column).setCellEditorthis );
      }
  
      public Component getTableCellRendererComponent(
          JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
      {
          if (hasFocus)
          {
              renderButton.setForeground(table.getForeground());
              renderButton.setBackground(UIManager.getColor("Button.background"));
          }
          else if (isSelected)
          {
              renderButton.setForeground(table.getSelectionForeground());
              renderButton.setBackground(table.getSelectionBackground());
          }
          else
          {
              renderButton.setForeground(table.getForeground());
              renderButton.setBackground(UIManager.getColor("Button.background"));
          }
  
          renderButton.setText( (value == null"" : value.toString() );
          return renderButton;
      }
  
      public Component getTableCellEditorComponent(
          JTable table, Object value, boolean isSelected, int row, int column)
      {
          text = (value == null"" : value.toString();
          editButton.setTexttext );
          return editButton;
      }
  
      public Object getCellEditorValue()
      {
          return text;
      }
  
      public void actionPerformed(ActionEvent e)
      {
          fireEditingStopped();
          
          try 
          {
        ServiceReference[] sr = findCompositionManagerImplementations();
        Object o = bc.getService(sr[0]);
        cm = (ICompositionManagero;  
        
        //Devo avviare i servizi restituiti dall'hashtable
        if services_discovered != null) {
          cm.runBundle( ( Hashtable services_discovered.elementAttable.getSelectedRow() ),11, ht );  
        
          }
          catch (Exception er
          {
        er.printStackTrace();
      }
          
      }
}

  
  /**
   @author Davide Migliacci
   
   * This function uses the internal OSGi service discovery to find a suitable implementation
   * of the IComunicationManager interface.
   */
  private ServiceReference[] findCompositionManagerImplementations() throws Exception
  {    
    ServiceReference[] cmi = null;
    try 
    {
      cmi = bc.getServiceReferences(ICompositionManager.class.getName()null);
    
    catch (Exception e
    {
      throw e;
    }
    return cmi;
  }

    public void appendts(String str)
    {
      append("[" new String((new Date((new Long(System.currentTimeMillis())).longValue())).toString()) "]\n" + str + "\n");      
    }   
    
    public void append(String str)
    {
      System.out.printlnstr );
    }
    
}