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

import org.omg.CORBA.*;
import java.util.*;
import com.wiley.compbooks.brose.chapter10.office.MeetingPackage.*;

/**
 * MeetingImpl.java
 *
 */

class MeetingImpl
    extends MeetingPOA
    implements java.io.Serializable
{
    private String purpose;
    private Vector participants;
    private DigitalSecretary organizer;
    private Room location;
    private Date time;
    private boolean cancelled = false;
    private String cancelReason = null;

    /** constructor */

    MeetingImpl(String purpose,
		Room location,
		Date time,
		DigitalSecretary organizer,
		DigitalSecretary[] participants )
    {
	// initialise private variables
	this.purpose = purpose;
	this.location = location;
	this.time = time;
	this.organizer = organizer;
	this.participants = new Vector();
	for( int i = 0; i < participants.length; i++ )
	{
	    this.participants.addElement(participants[i]);
	}
    }

    // attributes

    public String purpose()
    {
	return purpose;
    }

    public DigitalSecretary organizer()
    {
	return organizer;
    }

    public Room location()
    {
	return location;
    }

    public Date when()
    {
	return time;
    }

    public DigitalSecretary[] getParticipants()
	throws MeetingCancelled
    {
	if( cancelled )
	    throw new MeetingCancelled(cancelReason);

	DigitalSecretary[] result = new DigitalSecretary[participants.size()];
	participants.copyInto( result );
	return result;
    }


    public void addParticipant( DigitalSecretary participant )
	throws MeetingCancelled
    {
	if( cancelled )
	    throw new MeetingCancelled(cancelReason);
	participants.addElement( participant );
    }


    public void removeParticipant( DigitalSecretary participant )
	throws MeetingCancelled
    {
	if( cancelled )
	    throw new MeetingCancelled(cancelReason);
	participants.removeElement( participant );
    }


    public void cancel(String reason)
	throws MeetingCancelled
    {
	if( cancelled )
	    throw new MeetingCancelled(cancelReason);

	cancelReason = reason;
	notifyParticipants("Meeting " + purpose + " has been cancelled.");
	try
	{
	    _poa().deactivate_object( _poa().servant_to_id(this));
	}
	catch( Exception e )
	{
	    // ignore
	}
    }

    public void relocate(Room where, Date when)
	throws MeetingCancelled, SlotAlreadyTaken
    {
	where.book(when, organizer.name() );
	try
	{
	    location.cancelBooking( time );
	}
	catch( Exception e )
	{
	    e.printStackTrace(); // should not happen...
	}
	time = when;
	location = where;
	notifyParticipants("Meeting " + purpose + " has been relocated.");
    }

    void notifyParticipants(String message)
    {
	for( Enumeration e = participants.elements(); e.hasMoreElements(); )
	{
//	    ((DigitalSecretary)e.nextElement())._notify( message );
	}
    }

}
