package com.wiley.compbooks.brose.chapter10.office;

import java.io.*;
import java.util.Vector;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

public class BuildingImpl
    extends BuildingPOA
    implements java.io.Serializable
{
    transient POA factoryPOA;
    transient ORB orb;

    Vector roomList;
    Vector roomImplList;
    String name;

    public BuildingImpl(POA poa, ORB orb, String name)
    {	
	factoryPOA = poa;
	this.orb = orb;
	roomList = new Vector();
	roomImplList = new Vector();
	this.name = name;
    }

    /**
     * Init() must be called after deserializing a BuildingImpl object !
     */

    void init(POA poa, ORB orb)
    {	
	factoryPOA = poa;
	this.orb = orb;
	Vector v = new Vector();
	for( int i = 0; i < roomImplList.size(); i++ )
	{
	    ((RoomImpl)roomImplList.elementAt(i)).init(orb);
	}

	for( int i = 0; i < roomList.size(); i++ )
	{	 
	    String ior = (String)roomList.elementAt(i);	
	    Room r= RoomHelper.narrow( orb.string_to_object( ior ) );
	    if( r == null )
		throw new RuntimeException("Room is null" );

	    v.addElement( r );
	}
	roomList = v;
    }


    private void writeObject(java.io.ObjectOutputStream out)
	throws IOException
    {
	/*
	 * For serialization, object references are transformed
	 * into strings
	 */
	Vector v = new Vector();

	for( int i = 0; i < roomList.size(); i++ )
	{	  
	    v.addElement( orb.object_to_string( (org.omg.CORBA.Object)roomList.elementAt(i)));
	}
	roomList = v;
	out.defaultWriteObject();
    }

    public String name()
    {
	return name;
    }


    public Room create( String name )
    {
	try
	{
	    Room result = 
                RoomHelper.narrow(factoryPOA.create_reference_with_id(
                      name.getBytes(), 	       				  
                      "IDL:com/wiley/compbooks/brose/chapter10/office/Room:1.0" ) );
	    
	    roomList.addElement( result );

	    try
	    {
		RoomImpl room = new RoomImpl( name, _this(), orb );
		roomImplList.addElement( room );
		File f = new File( RoomLocator.filePrefix + name );
		
		FileOutputStream fout = new FileOutputStream(f);
	    
		ObjectOutputStream out = 
		    new ObjectOutputStream(fout);

		/* save state */
		out.writeObject( room );
	    
	    }
	    catch( IOException io )
	    {
		io.printStackTrace();
		System.err.println("Error opening output file "  + name );
		//		System.exit(1);
	    }

	    return result;
	}
	catch( Exception e )
	{
	    e.printStackTrace();
	}
	return null;
    }

    public Room[] list()
    {
	Room[] result = new Room[ roomList.size() ];
	roomList.copyInto( result );
	return result;
    }

}
