/*
 File:		TaskWrapper.m

 Description: 	This is the implementation of a generalized process handling class that that makes asynchronous interaction with an NSTask easier.  Feel free to make use of this code in your own applications.  TaskWrapper objects are one-shot (since NSTask is one-shot); if you need to run a task more than once, destroy/create new TaskWrapper objects.

 Author:		EP & MCF

 Copyright: 	© Copyright 2002 Apple Computer, Inc. All rights reserved.

 Disclaimer:	IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
 ("Apple") in consideration of your agreement to the following terms, and your
 use, installation, modification or redistribution of this Apple software
 constitutes acceptance of these terms.  If you do not agree with these terms,
 please do not use, install, modify or redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and subject
 to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs
 copyrights in this original Apple software (the "Apple Software"), to use,
 reproduce, modify and redistribute the Apple Software, with or without
 modifications, in source and/or binary forms; provided that if you redistribute
 the Apple Software in its entirety and without modifications, you must retain
 this notice and the following text and disclaimers in all such redistributions of
 the Apple Software.  Neither the name, trademarks, service marks or logos of
 Apple Computer, Inc. may be used to endorse or promote products derived from the
 Apple Software without specific prior written permission from Apple.  Except as
 expressly stated in this notice, no other rights or licenses, express or implied,
 are granted by Apple herein, including but not limited to any patent rights that
 may be infringed by your derivative works or by other works in which the Apple
 Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
                        GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  Version History: 1.1/1.2 released to fix a few bugs (not always removing the notification center,
                                                  forgetting to release in some cases)
                    1.3	   fixes a code error (no incorrect behavior) where we were checking for
                           if (task) in the -getData: notification when task would always be true.
                           Now we just do the right thing in all cases without the superfluous if check.
 */



#import "TaskWrapperNew.h"

#import <AppKit/NSWorkspace.h>
#import <AppKit/NSPanel.h>
#import <Foundation/Foundation.h>

#include <stdio.h>

@implementation TaskWrapper

// Do basic initialization
- (id)initWithController:(id <TaskWrapperController>)cont arguments:(NSArray *)args
{
    self = [super init];
    controller = cont;
    arguments = [args retain];
    
	//fprintf(stderr, "task wrap init with args\n");
	
    return self;
}

// tear things down
- (void)dealloc
{
	if ( ![task isTerminated] ) {
		[self stopProcess];
	}
	
	//fprintf(stderr, "task wrap dealloc\n");
	
    if (task) {
        [task removeObserver:self forKeyPath:@"isTerminated"];
    }
    
    [arguments release];
    [task release];
    [super dealloc];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSInteger newVal = (NSInteger)[change objectForKey:NSKeyValueChangeNewKey];
    NSLog(@"Terminated %ld", newVal);
    if (newVal) {
        [controller processFinished];
    }
}

// Here's where we actually kick off the process via an NSWorkspace.
- (void) startProcess
{
    // We first let the controller know that we are starting
    [controller processStarted];
    
    NSMutableDictionary * config = [NSMutableDictionary dictionary];
    NSArray * subarguments = [arguments objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, [arguments count]-1)]];
    
    [config setValue:subarguments forKey:NSWorkspaceLaunchConfigurationArguments];
    
    NSString * execpath = (NSString*)[arguments objectAtIndex:0];
    
    NSURL * launchurl = [NSURL  fileURLWithPath:execpath];
    NSError * error;
    
    //launchurl = [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:@"com.apple.TextEdit"];
    
    NSRunningApplication *  runtask = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:launchurl options:(NSWorkspaceLaunchNewInstance|NSWorkspaceLaunchDefault) configuration:config error:&error];
    
    
    if (runtask == nil) {
        [controller processFinished];
        NSRunAlertPanel(@"Error Starting GUI.  Please choose the correct application path.", @"%@", @"OK", nil, nil, [error description]);
    
        NSLog(@"Error starting process: %@", error);
    }
    else {
        task = [runtask retain];
        [task addObserver:self forKeyPath:@"isTerminated" options:NSKeyValueObservingOptionNew context:nil];
    }
    NSLog(@"Got running task: %p  for execpath: %@", task, execpath);
    
}

// If the task ends, there is no more data coming through the file handle even when the notification is
// sent, or the process object is released, then this method is called.
- (void) stopProcess
{

    // Make sure the task has actually stopped!
    if (task && ![task isTerminated]) {
        [task terminate];
    }
    
    // we tell the controller that we finished, via the callback, and then blow away our connection
    // to the controller.  NSTasks are one-shot (not for reuse), so we might as well be too.
    [controller processFinished];
    controller = nil;
}

@end

