/*
**  CommanderView.m
**
**  Copyright (c) 2003
**
**  Author: Yen-Ju Chen <yjchenx@hotmail.com>
**
**  Rewritten from AppController.h (GSCommander) 
**  by Philippe C.D. Robert <phr@3dkit.org>
**
**  This program is free software; you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation; either version 2 of the License, or
**  (at your option) any later version.
**
**  This program is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with this program; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "CommanderView.h"
#include "Command.h"

@implementation CommanderView 

- (id) initWithFrame: (NSRect) rect
{
  NSRect frame;
  NSTextField *tf;
  NSScrollView *scrollView;

  self = [super initWithFrame: rect];

  frame = NSMakeRect(0, rect.size.height-22, 60, 22);
  tf = [[NSTextField alloc] initWithFrame: frame];
  [tf setStringValue:@"Command: "];
//  [tf setAlignment: NSRightTextAlignment];
  [tf setBordered: NO];
  [tf setEditable: NO];
  [tf setBezeled: NO];
  [tf setDrawsBackground:NO];
  [tf setAutoresizingMask: NSViewMinYMargin];
  [self addSubview:tf];
  RELEASE(tf);

  frame = NSMakeRect(65, rect.size.height-22, rect.size.width-65, 22);
  commandField = [[NSTextField alloc] initWithFrame: frame];
//  [commandField setAlignment: NSLeftTextAlignment];
  [commandField setBordered: NO];
  [commandField setEditable: YES];
  [commandField setBezeled: YES];
  [commandField setDrawsBackground: YES];
  [commandField setTarget: self];
  [commandField setAction:@selector(setCommand:)];
  [commandField setAutoresizingMask: NSViewMinYMargin];
  [self addSubview:commandField];
  RELEASE(commandField);

  frame = NSMakeRect(0, rect.size.height-47, 60, 22);
  tf = [[NSTextField alloc] initWithFrame: frame];
  [tf setStringValue:@"Interval: "];
//  [tf setAlignment: NSRightTextAlignment];
  [tf setBordered: NO];
  [tf setEditable: NO];
  [tf setBezeled: NO];
  [tf setDrawsBackground:NO];
  [tf setAutoresizingMask: NSViewMinYMargin];
  [self addSubview:tf];
  RELEASE(tf);

  frame = NSMakeRect(65, rect.size.height-47, 40, 22);
  timeField = [[NSTextField alloc] initWithFrame: frame];
//  [timeField setAlignment: NSLeftTextAlignment];
  [timeField setBordered: NO];
  [timeField setEditable: YES];
  [timeField setBezeled: YES];
  [timeField setDrawsBackground: YES];
  [timeField setTarget: self];
  [timeField setAction:@selector(setTimeInterval:)];
  [timeField setAutoresizingMask: NSViewMinYMargin];
  [self addSubview:timeField];
  RELEASE(timeField);

  frame = NSMakeRect(110, rect.size.height-47, rect.size.width-110, 22);
  activeButton = [[NSButton alloc] initWithFrame: frame];
  [activeButton setTitle:@"Activate timed execution"];
  [activeButton setButtonType:NSSwitchButton];
  [activeButton setBordered:NO];
  [activeButton setTarget:self];
  [activeButton setAction:@selector(activateCommand:)];
  [activeButton setContinuous:NO];
  [activeButton setAutoresizingMask: NSViewMinYMargin];
  [self addSubview:activeButton];
  [activeButton sizeToFit];
  RELEASE(activeButton);

  frame = NSMakeRect(0, 0, rect.size.width, rect.size.height-52);
  scrollView = [[NSScrollView alloc] initWithFrame: frame];
  [scrollView setHasHorizontalScroller:NO];
  [scrollView setHasVerticalScroller:YES];
  [scrollView setBorderType:NSBezelBorder];
  [scrollView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];

  output = [[NSTextView alloc] initWithFrame:[[scrollView contentView] frame]];

  [output setFont:[NSFont userFixedPitchFontOfSize:12]];
  [output setRichText:NO];
  [output setEditable:NO];
  [output setSelectable:YES];
  [output setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable];
  [output setBackgroundColor:[NSColor whiteColor]];
  [[output textContainer] setWidthTracksTextView:YES];
  [[output textContainer] setHeightTracksTextView:YES];
  [output setHorizontallyResizable: NO];
  [output setVerticallyResizable: YES];
  [output setMinSize: NSMakeSize (0, 0)];
  [output setMaxSize: NSMakeSize (1E7, 1E7)];
  [[output textContainer] setContainerSize:
                               NSMakeSize([output frame].size.width,1e7)];
  [[output textContainer] setWidthTracksTextView:YES];

  [scrollView setDocumentView:output];
  [self addSubview:scrollView];

  RELEASE(scrollView);
  RELEASE(output);

  interval = 20;
  [timeField setStringValue: @"20"];

  [[NSNotificationCenter defaultCenter] addObserver: self 
                                           selector: @selector(taskEnded:) 
                                      name: NSTaskDidTerminateNotification 
                                    object: nil];

  return self;
}

- (void)dealloc
{
  if( command )
    {
      int result = NSRunAlertPanel(@"Command is still running",
                                   @"Previous command is still running. Want to stop it ?",                                                                                                        @"Yes", @"No", NULL);
                                   
     if (result == NSAlertAlternateReturn)
       {
          return;
       }  
      [command stop];
      
      RELEASE( command );
      command = nil;
    }

  [[NSNotificationCenter defaultCenter] removeObserver: self];

  if( [timer isValid] )
  {
    [timer invalidate];
  }
  [super dealloc];
}

- (void)setCommand:(id)sender
{
    NSString *comStr = [sender stringValue];
    NSArray  *tokens = [comStr componentsSeparatedByString:@" "];
    NSString *path;
    NSString *token;
    NSMutableArray *args;
    int      argCount;

    if( comStr == nil || [comStr isEqualToString:@""] )
    {
        NSRunAlertPanel(@"Attention!", @"This is not a valid command!", 
	                @"OK",nil,nil);
        return;
    }

    path = [tokens objectAtIndex:0];

    if( [path isEqualToString:@""] )
    {
        NSRunAlertPanel(@"Attention!", @"This is not a valid command!", 
	                @"OK",nil,nil);
        return;
    }

    // Now get all the arguemtns without any leading dash(es). This is a little
    // hacky, but it works for now...:-)

    argCount = [tokens count];
    args = [NSMutableArray array];

    if( argCount > 1 )
    {
	int i;

	for( i=1; i<argCount; i++ )
	{
	    token = [tokens objectAtIndex:i];

	    if( ![token isEqualToString:@""] )
            {
		[args addObject:token];
	    }
	}
    }

    if( [activeButton state] == NSOnState )
    {
	[activeButton setState:NSOffState];

	if( [timer isValid] )
	{
	    [timer invalidate];
	}
    }

    if( command )
    {
      int result = NSRunAlertPanel(@"Command is still running",
                                   @"Previous command is still running. Want to stop it ?",
                                   @"Yes", @"No", NULL);

     if (result == NSAlertAlternateReturn)
       {
          return;
       }
      [command stop];

      RELEASE( command );
      command = nil;
    }

    command = [[Command alloc] initWithCommand:path args:args];
    [command setTextView:output];
    [command executeCommand];
}

- (void) taskEnded: (NSNotification *) not
{
  if (([command task] == nil) ||  /* Task has be released */
     ([command task] == [not object])) /* Task is equal */
    {
      AUTORELEASE(command);
      command = nil;
    }
}

- (void)setTimeInterval:(id)sender
{
    interval = [sender intValue];

    if( interval < 1 )
    {
        interval = 20;
	[timeField setStringValue:@"20"];
    }

    if( [activeButton state] == NSOnState )
    {
	if( [timer isValid] ) 
	{
	    [timer invalidate];
	    timer = nil;
	}
	[self executeCommand];
    }
}

- (void)activateCommand:(id)sender
{
  switch ([[sender selectedCell] state]) 
  {
  case 0:
    if( [timer isValid] ) 
    {
      [timer invalidate];
      timer = nil;
    }
    break;
  case 1:
    [self executeCommand];
    break;
  }
}

- (void)executeCommand
{
    SEL exec = @selector(executeCommand);

    timer = [NSTimer scheduledTimerWithTimeInterval:interval
                                             target:command
                                           selector:exec
                                           userInfo:nil
                                            repeats:YES];
    [timer fire];
}

@end
