// $Id: EventHandler.cc,v 1.1 2003/08/31 00:38:11 vern Exp $

#include "EventHandler.h"
#include "Func.h"
#include "Scope.h"

EventHandler::EventHandler(const char* arg_name)
	{
	name = copy_string(arg_name);
	local = 0;
	type = 0;
	}

EventHandler::~EventHandler()
	{
	Unref(local);
	delete [] name;
	}

FuncType* EventHandler::FType()
	{
	if ( type )
		return type;

	ID* id = global_scope()->Lookup(name);
	if ( ! id )
		return 0;

	if ( id->Type()->Tag() != TYPE_FUNC )
		return 0;

	return type = id->Type()->AsFuncType();
	}

void EventHandler::SetLocalHandler(Func* f)
	{
	if ( local )
		Unref(local);

	Ref(f);
	local = f;
	}

void EventHandler::Call(val_list* vl)
	{
	if ( local )
		local->Call(vl);
	else
		{
		loop_over_list(*vl, i)
			Unref((*vl)[i]);
		}
	}

void EventHandler::AddRemoteHandler(addr_type ip, uint16 port)
	{
	receivers.append(new Receiver(ip, port));
	}

void EventHandler::RemoveRemoteHandler(addr_type ip, uint16 port)
	{
	loop_over_list(receivers, i)
		{
		if ( receivers[i]->ip == ip && receivers[i]->port == port )
			delete receivers.remove_nth(i);
		}
	}
