/* 
 * ToDoServer - implements DO connectivity to the ToDo application
 *
 * You may freely copy, distribute and reuse the code in this example.
 * This code is provided AS IS without warranty of any kind, expressed 
 * or implied, as to its fitness for any particular use.
 *
 * Copyright 1995 Ralph Zazula (rzazula@next.com).  All Rights Reserved.
 *
 */

#import "ToDoServer.h"
#import "_ToDoServer.h"
#import "ToDoController.h"
#import "FullCopyList.h"
#import "ToDoItemPublic.h"
#import <machkit/NXProtocolChecker.h>
#import <remote/transport.h>
#import <remote/NXConnection.h>

#define _controller _reservedToDoServer1

@implementation ToDoServer(Private)

- _setController:(id <ToDoServerProtocol>)aController
{
	_controller = aController;
	return self;
}

@end

@implementation ToDoServer

- init
{
	if(self = [super init]) {
		id protocolChecker = [[NXProtocolChecker alloc] initWithObject:self 
										forProtocol:@protocol(ToDoServerProtocol)];
		id conn = [NXConnection registerRoot:protocolChecker withName:TODO_PORT];
			
		[conn setDelegate:self];
		[conn runFromAppKit];
	}
	return self;
}

- free
{
	if(clientList) {
		clientList = [[clientList freeObjects] free];
	}
	return [super free];
}
	
- itemList
{
	int i;
	id toDoList, returnList = nil;

	if(!_controller) {
		return self;
	}
	
	toDoList = [_controller toDoList];
	if(toDoList ? [toDoList count] : 0) {
		returnList = [[FullCopyList alloc] init];
		for(i=0; i<[toDoList count]; i++) {
			[returnList addObject:[[ToDoItemPublic alloc] 
							initFromItem:[toDoList objectAt:i]]];
		}
	}
	return returnList;
}

- addItem:anItem
{
	if(_controller) {
		[_controller addItem:anItem];
	}
	return self;
}

- registerForNotification:(id <ToDoNotifications>)sender
{
	if(!clientList) {
		clientList = [[List alloc] init];
	}
	[clientList addObject:sender];
	return self;
}

/*** invalidation notification ***/

- senderIsInvalid:sender
{
	id remoteList = [sender remoteObjects];
	int i;
	
	if(remoteList) {
		/* Remove any clients the sender was vending from our clientList */
		for(i=0; i<[remoteList count]; i++) {
			[clientList removeObject:[remoteList objectAt:i]];
		}
		
		[remoteList free];
	}
	return self;
	
}

/*** as the NXConnection's delegate ***/

- connection:(NXConnection *)conn didConnect:(NXConnection *)newConn
{
	[newConn registerForInvalidationNotification:self];
	return newConn;
}

@end

