/////////////////////////////////////////////////////////////////////////
//
// © University of Southampton IT Innovation Centre, 2004
//
// Copyright in this library belongs to the IT Innovation Centre of
// 2 Venture Road, Chilworth Science Park, Southampton, SO16 7NP, UK.
//
// This software may not be used, sold, licensed, transferred, copied
// or reproduced in whole or in part in any manner or form or in or
// on any media by any person other than in accordance with the terms
// of the Licence Agreement supplied with the software, or otherwise
// without the prior written consent of the copyright owners.
//
// This software is distributed WITHOUT ANY WARRANTY, without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE, except where stated in the Licence Agreement supplied with
// the software.
//
//      Created by:             Stuart E. Middleton
//      Created date:           2004/04/30
//      Created for project:    GEMSS
//
/////////////////////////////////////////////////////////////////////////
//
//      Dependencies: None
//
/////////////////////////////////////////////////////////////////////////
//
//      Last commit info:       $Author: $
//                              $Date: $
//                              $Revision: $
//
/////////////////////////////////////////////////////////////////////////

package uk.ac.soton.itinnovation.gemss.utils.signalhandlers;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;

import eu.gemss.signals.negotiation.AcceptContractRequest;
import eu.gemss.signals.SignalHandler;
import eu.gemss.signals.Signal;

/**
 * Sample Signal handler for AcceptContractRequest signals
 */
public class AcceptContractRequestHandler extends JPanel implements SignalHandler {
      // interface data
      private static final String mTitleString = "Contract Acceptance Check";
      private JFrame mframe;
      private boolean mbExistingFrame;
      private JDialog mdialogModel;
      private Dimension mdimensionBestSize;

      // request object
      private AcceptContractRequest macceptContractRequest;

      // other
      private Logger mlogger = Logger.getLogger("uk.ac.soton.itinnovation.gemss.utils.signalhandlers.AcceptContractRequestHandler");

      /**
       * Default constructor that will cause a new frame object to be created just for
       * this dialogue box
       */
      public AcceptContractRequestHandler()
      {
            mframe = null;
            mbExistingFrame = false;
            mdimensionBestSize = null;
      }

      /**
       * Constructor that will re-use an existing frame object when creating
       * this dialogue box
       * @param frame JFrame object to use a parent to the dialogue box
       */
      public AcceptContractRequestHandler( JFrame frame ) throws Exception
      {
            if( frame == null ) throw new Exception("null frame object passed via constructor");
            mframe = frame;
            mbExistingFrame = true;
            mdimensionBestSize = null;
      }

      /**
       * Process the signal supplied by the Component Framework
       * @param signal signal to process
       */
      public void process( Signal signal )
      {
            Vector vector;
            Hashtable hash;
            Enumeration enum;
            String strWSDL;
            DefaultListModel listModel;

            try {
                  // check signal
                  if( signal instanceof eu.gemss.signals.negotiation.AcceptContractRequest ) {
                        // note signal
                        macceptContractRequest = (eu.gemss.signals.negotiation.AcceptContractRequest) signal;

                        // popup interface and show the WSLA for acceptance
                        initFrame();
                        initPanels( macceptContractRequest.getSummary(), macceptContractRequest.getWSLA() );

                        // show the dialogue box
                        // (model blocking call)
						mframe.toFront();
						mdialogModel.show();

                        // dispose of the gui
                        if( !mbExistingFrame ) mframe.dispose();
                        mdialogModel.dispose();

                        // tell the comp man that this signal was processed
                        macceptContractRequest.processed();

                  } // end of signal type check
                  else mlogger.log( Level.WARNING,"AcceptContractRequestHandler was sent the wrong signal type");
            }
            catch( Exception ex ) {
                  // do nothing just return the signal unhandled
                  mlogger.log( Level.SEVERE,"AcceptContractRequest signal handler failed",ex);
                  if( mframe != null && !mbExistingFrame ) mframe.dispose();
                  if( mdialogModel != null ) mdialogModel.dispose();
            }
      }

      /*
      * return the preferred size
      * @return preferred size
      */
      public Dimension getPreferredSize()
      {
            return mdimensionBestSize;
      }

      /*
      * Initialize the sub panels and make all interface controls. All sub panels are
      * added to this class (a panel itself). This method will pass any exceptions
      * through to caller.
      */
      private void initPanels( String strSummary, String strWSLA ) throws Exception
      {
            JPanel panel;
            JScrollPane scroll;
            JTextArea area;
			JLabel label;
			JButton button;
            BorderLayout overallLayout;

            // layout
            overallLayout = new BorderLayout();
            setLayout( overallLayout );

            // make label panel
            panel = new JPanel( new FlowLayout( FlowLayout.LEFT ) );
            add( panel,BorderLayout.NORTH );

            // make top label
            label = new JLabel( " Web Service Level Agreement ("+macceptContractRequest.getContracts()+" more to try if rejected)" );
            label.setPreferredSize( new Dimension( 750,25 ) );
            panel.add( label );

            // make label panel
            panel = new JPanel( new GridLayout(1,1) );
            add( panel,BorderLayout.CENTER );

			// make WSLA test area with scroll bars
            area = new JTextArea();
			area.setText( strSummary + "\n--- Actual WSLA reproduced below ---\n\n"+strWSLA );
			area.setEditable( false );
            scroll = new JScrollPane( area );
            scroll.setPreferredSize( new Dimension(750, 200) );
            panel.add( scroll );

            // make button panel
            panel = new JPanel( new FlowLayout( FlowLayout.RIGHT ) );
            add( panel,BorderLayout.SOUTH );

            // text
            label = new JLabel("if rejected the next best contract will be tried  ");
            panel.add( label );

            // select
            button  = new JButton("Accept");
            button.addActionListener( new CommandAction("Accept") );
            panel.add( button );

            // reject
            button = new JButton("Reject");
            button.addActionListener( new CommandAction("Reject") );
            panel.add( button );

            // record best size and pack
            mdimensionBestSize = overallLayout.preferredLayoutSize( this );
            mdialogModel.pack();
            mdialogModel.setLocationRelativeTo( mframe ); // not right in top left!
      }

      /* Initialize the main frame and dialogue box. This method will pass any exceptions through to caller. */
      private void initFrame() throws Exception
      {
            // Make sure we have nice window decorations
            UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
            JDialog.setDefaultLookAndFeelDecorated( true );

            // make frame and dialogue box (use apps frame object if passed)
            if( !mbExistingFrame ) {
                  mframe = new JFrame( mTitleString );
                  mframe.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            }
            mdialogModel = new JDialog( mframe, mTitleString, true );
            mdialogModel.getContentPane().add( this, BorderLayout.CENTER );
            mdialogModel.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
      }

      /* in-line class to handle button actions */
      private class CommandAction extends AbstractAction {
            // constructor
            public CommandAction( String name ) { super( name ); }
            // action handler
            public void actionPerformed(ActionEvent e)
            {
                  String strService;

                  if( e.getActionCommand().equals("Accept") ) {
                        // set the request signal result
                        macceptContractRequest.setAccept( true );
                        mlogger.log( Level.INFO,"User accepted WSLA" );

                        // exit
                        if( !mbExistingFrame ) mframe.dispose();
                        mdialogModel.dispose();
                  }
                  else if( e.getActionCommand().equals("Reject") ) {
                        // set the request signal result
                        macceptContractRequest.setAccept( false );
                        mlogger.log( Level.INFO,"User rejected WSLA" );

                        // exit
                        if( !mbExistingFrame ) mframe.dispose();
                        mdialogModel.dispose();
                  }
                  else mlogger.log( Level.WARNING,"Unhandled action from accept contract interface");
            }
      }
}