//
//  quick and dirty:
//     dialing with the ZyXEL modem 
//     by: Olaf Mueller <olaf@orest.escape.de>
//

#import "Dial.h"



@interface Dial (PrivateDialMethods)	

static int dodial (ChildParam *param) ;

@end



@implementation Dial

- init
{
	[super init] ;
	
	[NXApp loadNibSection:"Dial.nib" owner:self] ;
	[myWindow setFrameAutosaveName: "Dial"] ;
	return  self ;
}


- newNumber: (const char*)number
{
	if (number)
		[myNumberField setStringValue: number] ;
	[myNumberField selectText: self] ;
	[myWindow makeKeyAndOrderFront: self] ;
	return  self ;
}


- doDial: sender
{
	[myNumberField selectText: self] ;

	if (param.dialpid)
	{
//printf ("    killing dial\n") ;
		kill (param.dialpid,SIGINT) ;
	}
	else
	{
		strcpy (param.cmd,NXGetDefaultValue([NXApp appName],"dial_command")) ;
		strcpy (param.port,NXGetDefaultValue([NXApp appName],"device")) ;
//printf ("    starting %s on device %s\n",param.cmd,param.port);
		strcpy (param.number,[myNumberField stringValue]) ;
		param.reportField = myReportField ;
		param.button = myDialButton ;
		cthread_detach (cthread_fork((cthread_fn_t)dodial,(any_t)&param)) ;
	}
	return  self ;
}



// ------------------- private methods -------------------------

static int dodial (ChildParam *param)
{
	char	buffer [1000] , *cp ;
	int		pipeFrom[2] ;
	int		pipeTo[2] ;
	int		pidChild ;
	FILE	*fpFromChild ;
	int		toChild ;

	pipe (pipeFrom) ; pipe (pipeTo) ;
	switch (pidChild = vfork())
	{
	case -1:	// error
		break ;
	case 0:							// child
		dup2 (pipeTo[0],0) ;
		dup2 (pipeFrom[1],1) ;
		execl (param->cmd,param->cmd,param->port,param->number,0) ;
		break ;
	default:						// parent
		param->dialpid = pidChild ;
		[param->button setTitle: "Hangup"] ; NXPing () ;

		close (pipeFrom[1]) ;
		close (pipeTo[0]) ;

		if ((fpFromChild = fdopen(pipeFrom[0],"r")) != NULL)
		{
			toChild = pipeTo [1] ;
			while (fgets(buffer,sizeof(buffer),fpFromChild))
			{
				if ((cp = strstr(buffer,"dial: ")) == NULL)
					cp = buffer ;
				else
					cp = buffer + 6 ;
//printf ("      write: %s",cp) ;
				[param->reportField setStringValue: cp] ; NXPing () ;
			}
			fclose (fpFromChild) ;
		}
		else
		{
//printf ("    cannot open pipe to dial command\n") ;
		}
		[param->button setTitle: "Dial"] ; NXPing () ;
//printf ("    dial terminated\n") ;
		param->dialpid = 0 ;
		break ;
	}
	return  0 ;
}

@end
