import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import snmp.*;
import java.util.*;
import javax.swing.tree.*;

/**
   The panel that handles the SNMP operations
   @author Sugiharto Widjaja
   @version 10/30/02
*/
public class CommandPanel extends JPanel
{
   /**
      Construct the panel
      @param pane1 the MIB tree hierarchy
      @param pane2 the panel that handles connection
   */
   public CommandPanel(MIBHierarchy pane1, ConnectPanel pane2)
   {
      setLayout(new FlowLayout(FlowLayout.CENTER, 10,10));
      this.pane1 = pane1;
      this.pane2 = pane2;
      get = new JButton("Get SNMP variable");
      getNext = new JButton("Get Next SNMP variable");
      getChild = new JButton("Total Entities");
      getTable = new JButton("Get Table");
      getBulk = new JButton("Get Bulk");
      reset = new JButton("Clear");
      quit = new JButton("Quit MIB Browser");
      add(get);
      add(getNext);
      add(getBulk);
      add(getChild);
      add(getTable);
      add(reset);
      add(quit);
      getAddListener();
      getNextAddListener();
      getTableAddListener();
      getBulkAddListener();
      getTotalAddListener();
      resetMediaAddListener();
      quitaddListener();
   }

   /**
      Add an action listener to get button
   */
   private void getAddListener()
   {
      get.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            pane1.setCurrSelection();
            pane1.getMedia().append("\nSending Get SNMP variable to "
               + pane2.getHost() + " at 161\n");
            pane1.immediateValue();
            displayResult();
         }
      });
   }

   /**
      Add an action listener to total entities button
   */
   private void getTotalAddListener()
   {
      getChild.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            pane1.getMedia().append("\nSending Get Number of entities to "
               + pane2.getHost() + " at 161\n");
            int totEntries = pane1.totEntries();
            pane1.getMedia().append("There are " + totEntries + " entities under  " +
               "\"" + pane1.getMIBObject()+ "\"\n");
            ArrayList entityList = pane1.getEntityList();
            pane1.getMedia().append("Entities: ");

            if (entityList.size() != 0)
               pane1.getMedia().append(entityList.toString() + " ");
            else
               pane1.getMedia().append("no entities found");

            pane1.getMedia().append("\n");
         }
      });
   }

   /**
      Add an action listener to get next button
   */
   private void getNextAddListener()
   {
      getNext.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            pane1.nextValue();
            pane1.highLightNext();
            if (pane1.isFind())
            {
               pane1.nextValue();
               pane1.highLightNext();
            }
            pane1.getMedia().append("\nSending Get Next SNMP variable to "
               + pane2.getHost() + " at 161\n");
            if (!pane1.isEnd())
               displayResult();
            else
               pane1.getMedia().append("End of MIB-2 Browser\n");
         }
      });
   }

   /**
      Add an action listener to get bulk button
   */
   private void getBulkAddListener()
   {
      getBulk.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            try
            {
               String in = JOptionPane.showInputDialog
                  ("Enter the max number of repetitions");
               maxRep = Integer.parseInt(in);
               pane1.getMedia().append("\nMax number of " +
                  "repetitions set to " + maxRep + "\n");
               pane1.getMedia().append("Sending Get Bulk to "
                     + pane2.getHost() + " at 161\n");
               for (int i = 0; i < maxRep; i++)
               {
                  pane1.nextValue();
                  pane1.highLightNext();
                  if (pane1.isFind())
                  {
                     pane1.nextValue();
                     pane1.highLightNext();
                  }
                  if (!pane1.isEnd())
                     displayResult();
                  else
                     pane1.getMedia().append("End of MIB-2 Browser\n");
               }
            }
            catch(NumberFormatException ex)
            {
               pane1.getMedia().append("Must enter an integer " +
                 "for the max repetitions\n");
            }
         }
      });
   }

   /**
      Add an action listener to get table button
   */
   private void getTableAddListener()
   {
      getTable.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            pane1.setCount(0);
            pane1.nextValueTable();
            pane1.getMedia().append("\nSending Get Table to "
                  + pane2.getHost() + " at 161\n");
            if (pane1.isTable())
            {
               pane1.highLightNext();
               int count = pane1.getCount();
               for (int i = 0; i < count; i++)
               {
                  pane1.nextValueTable();
                  pane1.highLightNext();
                  displayResult();
               }
            }
            else
            {
               pane1.getMedia().append("The entity that you are selected is " +
                    "not a table, use get or get next instead\n");
            }
         }
      });
   }

   /**
      Add an action listener to reset button.
   */
   private void resetMediaAddListener()
   {
      reset.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            pane1.getMedia().setText("");
         }
      });
   }

   /**
      Add an action listener to quit button
   */
   private void quitaddListener()
   {
      quit.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {
            System.exit(0);
         }
      });
   }

   /**
      Connect to the host and try to get the MIB object value
      @throws Exception
   */
   private void displayResult()
   {
      try
      {
         InetAddress host = InetAddress.getByName(pane2.getHost());
         String community = pane2.getCommunity();
         String currMIBObject = pane1.getMIBObjectID();
         if(host != null && community != null && currMIBObject != null)
         {
            if (currMIBObject.equals(""))
            {
               pane1.getMedia().append("The entry you choosed is not accessible. " +
                   "Please use get next or get bulk instead\n");
            }
            else
            {
               comInterface = new SNMPv1CommunicationInterface(version, host, community);
               SNMPVarBindList newVars = comInterface.getMIBEntry(currMIBObject);
               SNMPSequence pair = (SNMPSequence)(newVars.getSNMPObjectAt(0));
               SNMPObject snmpValue = pair.getSNMPObjectAt(1);
               pane1.getMedia().append("System." + pane1.getMIBObject() + ".0"
                  + " : " + snmpValue.toString() + "\n");
            }
         }

      }
      catch(SNMPGetException ex)
      {
         pane1.getMedia().append(pane1.getMIBObject() + " : Not available for retrieval\n");
      }
      catch(SocketTimeoutException ex)
      {
         pane1.getMedia().append("Connection timed-out\n");
      }
      catch(UnknownHostException ex)
      {
         pane1.getMedia().append("Invalid hostname\n");
      }
      catch(SocketException ex)
      {
         pane1.getMedia().append("Error in creating socket\n");
      }
      catch(IOException ex)
      {
         pane1.getMedia().append("Error in I/O operation\n");
      }
      catch(SNMPBadValueException ex)
      {
         pane1.getMedia().append("Inappropriate data\n");
      }
   }

   // To communicate with SNMP entities
   private SNMPv1CommunicationInterface comInterface;
   // The MIB hierarchy tree
   private MIBHierarchy pane1;
   // The connect panel
   private ConnectPanel pane2;
   // The get button
   private JButton get;
   // The get next button
   private JButton getNext;
   // Get the number of entities
   private JButton getChild;
   // Get the table entities
   private JButton getTable;
   // Get bulk operation
   private JButton getBulk;
   // The quit button
   private JButton quit;
   private JButton reset;
   // The SNMP version
   private int version = 0;
   // how many entities that the user wants in getBulk
   private int maxRep;
}