// Copyright 2012 Tony Garnock-Jones <tonygarnockjones@gmail.com>.
//
// This file is part of Hop.
//
// Hop 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 3 of the License, or (at your
// option) any later version.
//
// Hop 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 Hop.  If not, see <http://www.gnu.org/licenses/>.
//

#import "hopOsxAppDelegate.h"
#include <sys/stat.h>

#define HOP_STARTUP_DEADLINE_SECONDS 30

@implementation hopOsxAppDelegate

@synthesize window;
@synthesize webview;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	task = [NSTask new];
	
	[[NSNotificationCenter defaultCenter]
	 addObserver: self
	 selector: @selector(mainWindowClosed:)
	 name: NSWindowWillCloseNotification
	 object: window];
	
	[[NSNotificationCenter defaultCenter]
	 addObserver: self
	 selector: @selector(taskStatusChanged:)
	 name: NSTaskDidTerminateNotification
	 object: nil];
	
	NSString *serverBinaryPath = [[NSBundle mainBundle] resourcePath];
	[task setCurrentDirectoryPath: serverBinaryPath];
	NSString *serverBinary = [serverBinaryPath stringByAppendingPathComponent: @"hop_server.native"];
	[task setLaunchPath: serverBinary];
	
	NSString *readyFile = [NSTemporaryDirectory() stringByAppendingPathComponent: @"hop.ready."];
	readyFile = [readyFile stringByAppendingFormat: @"%d", getpid()];
	char const *readyFileUtf8 = [readyFile UTF8String];
	unlink(readyFileUtf8);
	
	[task setArguments: [NSArray arrayWithObjects: @"--ready-file", readyFile, nil]];
	
	@try {
		[task launch];
	}
	@catch (NSException *e) {
		NSLog(@"Could not launch server %@: %@", serverBinary, [e reason]);
		[NSApp terminate: self];
		@throw;
	}
	
	int foundReadyFile = 0;
	time_t startTime = time(NULL);
	while ([task isRunning] && time(NULL) - startTime < HOP_STARTUP_DEADLINE_SECONDS) {
		struct stat s;
		if (lstat(readyFileUtf8, &s) != -1) {
			foundReadyFile = 1;
			break;
		}
		if (errno != ENOENT) {
			perror("lstat of readyFileUtf8");
			exit(EXIT_FAILURE);
		}
		usleep(100000);
	}
	unlink(readyFileUtf8);

	if (!foundReadyFile) {
		NSLog(@"Server did not start up within %d seconds.", HOP_STARTUP_DEADLINE_SECONDS);
		[NSApp terminate: self];
		return;
	}
	
	[[webview mainFrame] loadRequest:
	 [NSURLRequest requestWithURL:
	  [NSURL URLWithString: @"http://localhost:5678/"]]];
}

- (void) applicationWillTerminate: (NSNotification *) notification {
	if ([task isRunning]) {
		[task terminate];
	}
}

- (void) taskStatusChanged: (NSNotification *) aNotification {
	[NSApp terminate: self];
}

- (void) mainWindowClosed: (NSNotification *) aNotification {
	[NSApp terminate: self];
}

@end
