/* 
 * Command.m created by probert on 2001-12-29 17:36:43 +0000
 *
 * Project GSCommander
 *
 * Created with ProjectCenter - http://www.gnustep.org
 *
 * $Id: Command.m,v 1.1.1.1 2001/12/30 12:42:37 probert Exp $
 */

#import "Command.h"

@implementation Command

- (id)initWithCommand:(NSString *)comm args:(NSArray *)arguments
{
    if( self = [super init] )
    {
	args = RETAIN(arguments);
        command = RETAIN(comm);

    }
    return self;
}

- (void)dealloc
{
    RELEASE(args);
    RELEASE(command);

    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [super dealloc];
}

- (void)setTextView:(NSTextView *)view
{
    AUTORELEASE(output);
    output = RETAIN(view);

    [output setString:@""];
}

- (void)log:(NSNotification *)aNotif
{
  NSData *data;

  if((data = [fileHandle availableData])) 
  {
      NSString *s = [[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]];

      [output replaceCharactersInRange:NSMakeRange([[output string] length],0) withString:s];

      [output replaceCharactersInRange:NSMakeRange([[output string] length],0) withString:@"\n"];
  }
}

- (void)executeCommand
{
  if( output == nil )
  {
    NSRunAlertPanel(@"Attention!", @"No output view available!",@"OK",nil,nil);
    return;
  }

  [output setString:@""];

  pipe = [[NSPipe alloc] init];
  fileHandle = [pipe fileHandleForReading];
  RETAIN(fileHandle);

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(log:) name:NSFileHandleDataAvailableNotification object:fileHandle];

  task = [[NSTask alloc] init];
  [task setArguments:args];
  [task setLaunchPath:command];
  [task setStandardOutput:pipe];
  [task setStandardError:pipe];

  [fileHandle waitForDataInBackgroundAndNotify];
  [task launch];
  [task waitUntilExit];

  [[NSNotificationCenter defaultCenter] removeObserver:self];

  RELEASE(fileHandle);
  RELEASE(pipe);
  RELEASE(task);
  task = nil;
}

- (void)stop
{
    if( task && [task isRunning] )
    {
        [task terminate];

	[[NSNotificationCenter defaultCenter] removeObserver:self];

	if( output )
	{
	    RELEASE( output );
	    output = nil;
	}
    }
}

@end
