

/* 	STAppClient.m written by Robert Vasvari 1/95
	This class connects to the remote server, and implements
	basic error handling (if the server goes down it will
	automatically reconnect.
	
	

*/

#import "STDefines.h"
#import "STAppClient.h"
#import "STAppServer.h"


@implementation STAppClient

/* this is a sample method to connect to a fictitious server app. 
	servernameProxy is an instance variable that represents
	a connection to a server. You app accesses the server
	like this:
	[[STAppClient servername] remoteMessage:arg];
	
+ servername 
{
	if(!servernameProxy)
	 {	servernameProxy=[self connectToApp:
	 	[NSString stringWithCString:servername]
			usingProtocol:@protocol(servernameProtocol)];
	 }
	return [servernameProxy remoteServer];
}

*/

+ connectToApp:(NSString *)anAppName usingProtocol:(Protocol *)aProtocol
{	
id newClient=[[self alloc] init];
	
	[newClient setProtocol:aProtocol];
	[newClient setServerName:anAppName];
	if([newClient getRemoteServer])
		return newClient;
	else return nil;
}

- setProtocol:aProtocol
{	proto=aProtocol;
	return self;
}

- setServerName:(NSString *)anAppName
{	if(serverName) [serverName autorelease];
	serverName=[anAppName retain];
	return self;
}

- getRemoteServer
{	
char buf[1024];
NSString *s;

	if(!serverName) 
	 { 	NXRunAlertPanel("Alert","Do not know who to connect to!",
	    NULL,NULL,NULL);
	 	return self;
	 }
	s=[NSString stringWithFormat:@"%@", serverName];
	
	gethostname(buf,1024);

	/* this will start it if it isn't running */
	if(NXPortFromName([serverName cString], NULL)!=PORT_NULL)
	 { 	
		
		/* get the proxy (times out after a minute) */
		remoteServer=[NXConnection connectToName:
					[s cString] onHost:buf];
		
		/* To make sure the app is fully initialized
		   you should send a message to the server
		   that returns a value. That will block your
		   app until the server is fully initialized:
		 */
		   [(STAppServer *)remoteServer appName];
	 }
	else
	 { 	NXRunAlertPanel("Alert","Cannot find %s",
	    NULL,NULL,NULL, [serverName cString]);
		return nil;
	 }

    [[remoteServer connectionForProxy]
	    registerForInvalidationNotification:self];

	[remoteServer setProtocolForProxy:proto];
	return self;
}

- senderIsInvalid:sender
{
	//printf("in senderIsValid\n");
	
	/* if the server quits, the system frees the proxy */
	remoteServer=nil;
    return self;
}

- remoteServer
{	
	/* make sure we have a connection */
	if(!remoteServer) [self getRemoteServer];
	return remoteServer;
}


@end

