/*
 * Client.java
 *
 * Author: Jonathan Boldiga
 * Date: JUN 16 2002
 *
 * Description: This is an adapted/extended version of Kartik Pandya's
 *				chat client/server. It has been ported for use on Orbix 2.0
 *				and greater	and also now includes a GUI.
 *
 * Copyright (c) 1993-2001 IONA Technologies PLC.
 *  			All Rights Reserved
 *
*/

package Chat;

import java.io.*;
import java.util.Hashtable;
import java.util.Date;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class Client {

  public static String RequestedBy;
  public static boolean Responding;

  public static void main (String args[]){
  	Responding = false;
    RequestedBy = null;
    ORBChatSplash ocs = new ORBChatSplash(new Frame());

  	try{

	    System.out.println("Beginning ORBChat");

	    ORB orb = ORB.init(args, null);

	    org.omg.CORBA.Object objref = null;


	    org.omg.CORBA.Object poa_obj = orb.resolve_initial_references("RootPOA");

		org.omg.PortableServer.POA root_poa = org.omg.PortableServer.POAHelper.narrow(poa_obj);

	    org.omg.PortableServer.POAManager poa_manager = root_poa.the_POAManager();

		// Create a PERSISTENT POA named 'simple_chat', beneath the root^M
		//
		org.omg.CORBA.Policy[] policies=new org.omg.CORBA.Policy[2];

		policies[0]=root_poa.create_lifespan_policy(org.omg.PortableServer.LifespanPolicyValue.PERSISTENT);
		policies[1]=root_poa.create_id_assignment_policy(org.omg.PortableServer.IdAssignmentPolicyValue.USER_ID);

		/*The date at which the client program was loaded is saved to identify the client. Unless two people sign-on
		  at the exact same second, then there should be no problems.*/

		Date dt = new Date();
	    String dateLabel = dt.toString();


		org.omg.PortableServer.POA persistent_poa= root_poa.create_POA(dateLabel, poa_manager, policies);


		// Create and activate the servants, giving it an id and making
		// them available for use.
		System.out.println("Creating objects");
		ChatClientImpl my_servant = new ChatClientImpl();
		byte[] oid= dateLabel.getBytes();

	    persistent_poa.activate_object_with_id(oid,my_servant);
		poa_manager.activate();

	    Chat.ChatRemote chatRemote = null;
	    Chat.ChatLocal chatLocal = null;

	    String ior_file = null;
	    for (int i = 0 ; i < args.length - 1 ; i++)
	    {
	      if ("-file".equals(args[i]))
	      {
	        ior_file = args[i + 1];
	      }
	    }
	    if (ior_file == null)
		    {
       System.out.println("usage: Client -file <objref_filename>");
	       System.exit(1);
	    }

	    // Invoke method on the object
	    //

	    System.out.println("Invoking method on the object");

	    objref = import_object(orb, ior_file);

	    chatRemote = ChatRemoteHelper.narrow(objref);

	    ocs.closeMe();

		runChat(chatRemote, orb, null, false);
	    orb.shutdown(true);
	}
	catch(org.omg.CORBA.ORBPackage.InvalidName ex)
	{
	  System.out.println("Failed to obtain root poa " + ex );
	}
	catch(org.omg.PortableServer.POAPackage.WrongPolicy ex)
	{
	  System.out.println("Invalid POA policy " + ex );
	}
	catch(org.omg.PortableServer.POAPackage.ServantAlreadyActive ex)
	{
	  System.out.println("POA servant already active " + ex );
	}
	catch(org.omg.PortableServer.POAManagerPackage.AdapterInactive ex)
	{
	  System.out.println("POAManager activate failed" + ex );
	}
	catch(org.omg.PortableServer.POAPackage.ObjectAlreadyActive ex)
	{
	  System.out.println("Object activation failed" + ex);
	}
	catch(org.omg.PortableServer.POAPackage.AdapterAlreadyExists ex)
	{
	  System.out.println("Adapter creation failed" + ex);
	}
	catch(org.omg.PortableServer.POAPackage.InvalidPolicy ex)
	{
	  System.out.println("Adapter creation failed" + ex);
	}

}


public static void runChat(ChatRemote cr, ORB orb, String user, boolean flag){
	Login lg = new Login(cr, orb);
	if(flag == false){
	   	lg.pack();
	   	lg.setVisible(true);
	   	orb.run();
	}
	else if(flag == true){
		if(user.equals("administrator")){
			Moderator mod = new Moderator(cr);
			mod.pack();
			mod.setVisible(true);
		}
		else{
			ClientGUI clientG = new ClientGUI(cr, user);
			clientG.pack();
			clientG.setVisible(true);
		}
	}

}


  /**
   * reads and destringifies an object reference stored in a file.
   */

  public static org.omg.CORBA.Object import_object(ORB orb, String filename)
  {
    String ior = null;

    System.out.println("Reading object reference from " + filename);

    try
    {
      FileInputStream fis=new FileInputStream(filename);
      InputStreamReader osr=new InputStreamReader(fis);
      BufferedReader br=new BufferedReader(osr);
      ior = br.readLine();
      br.close();

      return orb.string_to_object(ior);
    }
    catch(Exception e)
    {
      System.out.println("Error opening file " + filename);
      return null;
    }
  }
}


/**
 * This is an example of using skeleton inheritance to create
 * a servant.  The implementation class derives directly from
 * the POA skeleton, and implements each of the skeleton methods.
 */
class ChatClientImpl extends ChatLocalPOA
{
	public boolean ask(String key)
    {
        Client.Responding = true;
        Client.RequestedBy = key;
        return true;

    }
    public void receive(String message, String source)
    {
		ClientGUI.displayResult(message, source);
    }

    public void update(){
		ClientGUI.refreshList();
	}

}



