package cnrg.itx.gtwy.pbx;

/**
 * JtapiHandler Class 
 *
 *  This program is the service class used to dial and hangup.
 *  It uses Lucent's implementation of JTAPI to make a call. The application
 *  does the following for every call made:
 *  
 *      1) Create Provider object (only when the JtapiHandler is created)
 *      2) Create Address object for Calling Device
 *      3) Create Terminal object for Calling Device
 *      4) Create a Call object
 *      5) Make call using the Call.connect method
 *      6) When "Hang-up" is requested, drop call using Connection.disconnect() method
 *	7) Shutdown the provider (NO NEED TO DO THIS)
 *  
 *  The JtapiPeer object is created once upon initialization of the application.
 *
 *  Parameters required:
 *      Tlink Name      name for PBX driver as advertised by Tserver
 *      Jtapi Server    hostname or IP address of machine running the Jtapi server
 *      Login           login as administered on the NT domain
 *      Password        password administered for login
 *      Calling Device  device that will originate the call
 *      Called Device   destination number
 */

import javax.telephony.*;
import javax.telephony.events.*;
import javax.telephony.callcontrol.*;
import cnrg.itx.signal.*;

public class JtapiHandler{
   private String ME = "JtapiHandler :";

   public JtapiPeer   jtapiPeer;
   public Provider    provider;

   private boolean LOG = false;
   private String serviceID = "LUCENT#G3_SWITCH#CSTA#PLAYPEN";
   private String login;
   private String password;
        
   /**
    * This creates a JtapiHandler object, logging us into the Tserver.
    * @param     log_option   true for debugging output
    * @param     l            String giving our login id
    * @param     p            String giving our password
    * @exception PBXSignalingException
    */
   JtapiHandler(boolean log_option, String l, String p)
      throws PBXSignalingException {
   // store JtapiHandler's values
      LOG = log_option;
      login = new String(l);
      password = new String(p);
      if (LOG) System.out.println(ME + "being created");
      init();
      login();//login to get the provider setup and ready to make calls.
   }

   /**
    * If our provider dies, this routine should try to kick it back
    * into action
    */
   protected void kickProvider() throws PBXSignalingException {
      if ( LOG ) System.out.println (ME + "trying to bring a new " +
         "provider into service");
      login();
   }

   /**
    * Private method to set up the provider
    */
   private void init() throws PBXSignalingException {
            
      String[]    services = null;//ok
                
      if ( !initJtapi() ) {
	 System.out.print( "Error: JtapiPeer could not be created.  Verify your Jtapi client install.\n\n");
	 throw ( new PBXSignalingException
	    ("JtapiPeer could not be created"));
      }                
     // get tlinks administered
     try {
	if (LOG) System.out.println(ME + "Get Services");
        services = jtapiPeer.getServices();
        if (LOG) System.out.println(ME + "Got Services");
     } catch (PlatformException e) {
        System.out.print( ME + "JtapiPeer.getServices() " +
	   "caught PlatformException\n\n" );
     }

     //display services/administered tlinks
     if ( LOG ) {
        System.out.println(ME + "Services setup are the following:");
        if (services != null) 
           for ( int i=0; i < services.length; i++ )
              System.out.println( services[i] );
        else System.out.println("No services!");
     } // end if LOG

  } // ends init

    
   /**
    * This method creates the JtapiPeer
    */
    private boolean initJtapi() {

    // 1) create JtapiPeer object
        try {
        // get Lucent's implementation of the JtapiPeer object
           jtapiPeer = JtapiPeerFactory.getJtapiPeer( "com.lucent.jtapi.tsapi.TsapiPeer" );
	   if (LOG) System.out.println (ME + 
	   "Got JtapiPeer Object! its name is " + jtapiPeer.getName() );
        }
        catch (JtapiPeerUnavailableException e) {
	   System.out.println("JtapiPeerFactory.getJtapiPeer: caught JtapiPeerUnavailableException\n");
        }
            
        if ( jtapiPeer == null ) {
           System.out.println(ME + "Error: JtapiPeer could not be created\n");
           return false;
        } else {
	   if (LOG) System.out.println(ME + "JtapiPeer created successfully\n");
        }
        return true;
    } // ends initJtapi

   /**
    * This method creates the Provider, after authenticating with the Tserver
    */
    private void login() throws PBXSignalingException {
        String          providerString;

        provider = null;
        providerString = serviceID + ";login=" + login + ";passwd=" + password + ";";

        if (LOG) System.out.println(ME + providerString);
        try {
           // create provider
          if ( jtapiPeer != null ) {
             if (LOG) System.out.println(ME + "getting provider");
             provider = jtapiPeer.getProvider(providerString);
             if (LOG) System.out.println(ME + "got provider");
        } else {
	   if (LOG) System.out.println(ME + "Error: No provider\n");
	   System.out.print("Error: JtapiPeer could not be created\n\n");
	   throw (new PBXSignalingException 
	      ("Could not create JtapiPeer") );
        }
        if (provider != null) {
           if (LOG) System.out.print(ME + 
	      "Waiting for the provider to come into service");
           while (provider.getState() != Provider.IN_SERVICE)
              {
                 Thread.sleep(1000);
                 if (LOG) System.out.print(".\n");
              }
           if (LOG) System.out.println(ME + "Provider is in service");
        } else {
           System.out.println("Error: Provider would not come up");
	   throw (new PBXSignalingException
	      ("Provider would not come into service") );
        }
     }
     catch (PlatformException e) {
	System.out.print("JtapiPeer.createProvider(): caught PlatformException\n\n");
	e.printStackTrace();
	throw new PBXSignalingException ("JtapiHandler failed to create " +
	   "a provider because " + e.toString() ) ;
     }
     catch (Exception e) {
        System.out.print("JtapiPeer.createProvider(): caught PlatformException\n\n");
        e.printStackTrace();
	throw new PBXSignalingException ("JtapiHandler failed to create " +
	   "a provider because " + e.toString() ) ;
     }
    }


    
    /**
     * Shuts down the provider.  This routine is not really needed.
     */
    private void logout() {
            
       if (provider != null ) {
                            
          if ( provider.getState() == Provider.IN_SERVICE ) {
             if (LOG) System.out.print(ME + "Shutting down provider...\n\n");
             try {
                provider.shutdown();
             }
             catch ( PlatformException e ) {
                System.out.print( "ProviderFrame.shutdown(): caught PlatformException\n\n" );
             }
	     finally {
                provider = null;
             }
	  } // ends if
        } // ends if
    }
    

    public void stop() {
    // before terminating application, we should shutdown provider
       logout();
    }

    /**
     * this method simply returns a provider
     */
    public Provider getProvider(){
       return provider;
    }
}

/* redirectButton_Clicked()
         * when redirect button clicked it redirects the current call connection to
         * 45515
         */
/*        void redirectButton_Clicked(Event event) {
                if (myConnection != null) {
                        CallControlConnection ccconn = (CallControlConnection)destConnection;

                        try {
                                ccconn.redirect("45515");
                                System.out.println("Call Forwarded");
                        } catch (Exception e ) {
                                System.out.println("Cannot forward " + e );
                        }
                }
        }*/

