/* 
 * AppController.m created by phr on 2000-08-27 11:38:58 +0000
 *
 * Project TestApp
 *
 * Created with ProjectCenter - http://www.gnustep.org
 *
 * $Id: AppController.m,v 1.1.1.1 2001/12/30 12:42:37 probert Exp $
 */

#import "AppController.h"
#import "Command.h"

@interface AppController (InterfaceCreation)

- (void)_createInterface;

@end

@implementation AppController (InterfaceCreation)

- (void)_createInterface
{
  unsigned int style = NSTitledWindowMask    | 
                       NSResizableWindowMask |
                       NSMiniaturizableWindowMask;
  NSView *view;
  NSRect frame;
  NSTextField *tf;
  NSScrollView *scrollView;

  frame = NSMakeRect(100,100,480,224);
  window = [[NSWindow alloc] initWithContentRect:frame
                             styleMask:style
                             backing:NSBackingStoreBuffered
                             defer:NO];
  [window setDelegate:self];
  [window setTitle:@"GNUstep Unix Commander"];
  [window setMinSize:NSMakeSize(480,224)];
  [window setReleasedWhenClosed:NO];
  view = [window contentView];

  tf = [[NSTextField alloc] initWithFrame:NSMakeRect(16,8,56,21)];
  [tf setStringValue:@"Command"];
  [tf setAlignment: NSRightTextAlignment];
  [tf setBordered: NO];
  [tf setEditable: NO];
  [tf setBezeled: NO];
  [tf setDrawsBackground:NO];
  [view addSubview:tf];
  RELEASE(tf);

  commandField = [[NSTextField alloc] initWithFrame:NSMakeRect(80,8,360,21)];
  [commandField setAlignment: NSLeftTextAlignment];
  [commandField setBordered: NO];
  [commandField setEditable: YES];
  [commandField setBezeled: YES];
  [commandField setDrawsBackground: YES];
  [commandField setAction:@selector(setCommand:)];
  [view addSubview:commandField];
  RELEASE(commandField);

  tf = [[NSTextField alloc] initWithFrame:NSMakeRect(16,32,56,21)];
  [tf setStringValue:@"Interval"];
  [tf setAlignment: NSRightTextAlignment];
  [tf setBordered: NO];
  [tf setEditable: NO];
  [tf setBezeled: NO];
  [tf setDrawsBackground:NO];
  [view addSubview:tf];
  RELEASE(tf);

  timeField = [[NSTextField alloc] initWithFrame:NSMakeRect(80,32,40,21)];
  [timeField setAlignment: NSLeftTextAlignment];
  [timeField setBordered: NO];
  [timeField setEditable: YES];
  [timeField setBezeled: YES];
  [timeField setDrawsBackground: YES];
  [timeField setAction:@selector(setTimeInterval:)];
  [view addSubview:timeField];
  RELEASE(timeField);

  activeButton = [[NSButton alloc] initWithFrame:NSMakeRect(136,35,160,15)];
  [activeButton setTitle:@"Activate timed execution"];
  [activeButton setButtonType:NSSwitchButton];
  [activeButton setBordered:NO];
  [activeButton setTarget:self];
  [activeButton setAction:@selector(activateCommand:)];
  [activeButton setContinuous:NO];
  [view addSubview:activeButton];
  [activeButton sizeToFit];
  RELEASE(activeButton);

  scrollView = [[NSScrollView alloc] initWithFrame:NSMakeRect (0,64,480,160)];
  [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];
  [view addSubview:scrollView];

  RELEASE(scrollView);
  RELEASE(output);
}

@end

@implementation AppController

static NSDictionary *infoDict = nil;

+ (void)initialize
{
  NSMutableDictionary *defaults = [NSMutableDictionary dictionary];

  /*
   * Register your app's defaults here by adding objects to the
   * dictionary, eg
   *
   * [defaults setObject:anObject forKey:keyForThatObject];
   *
   */
  
  [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
  [[NSUserDefaults standardUserDefaults] synchronize];
}

- (id)init
{
  if ((self = [super init])) {
      [self _createInterface];

      interval = 20;
      [timeField setStringValue:@"20"];
  }
  return self;
}

- (void)dealloc
{
  RELEASE( window );

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

  [super dealloc];
}

- (void)awakeFromNib
{
}

- (void)applicationDidFinishLaunching:(NSNotification *)notif
{
  [window center];
  [window makeKeyAndOrderFront:self];
}

- (BOOL)applicationShouldTerminate:(id)sender
{
  return YES;
}

- (void)applicationWillTerminate:(NSNotification *)notification
{
}

- (BOOL)application:(NSApplication *)application openFile:(NSString *)fileName
{
  return NO;
}

- (void)showPrefPanel:(id)sender
{
}

- (void)showInfoPanel:(id)sender
{
  [[NSApplication sharedApplication] orderFrontStandardInfoPanel:sender];
}

- (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 )
    {
        [command stop];

	AUTORELEASE( command );
	command = nil;
    }

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

- (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
