/*
 Copyright 2008 Google Inc.
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
#import "SampleController.h"
#import <WebKit/WebFrame.h>
#import <WebKit/WebScriptObject.h>

/*const NSString *PluginURL =
 @"http://earth-api-samples.googlecode.com/svn/trunk/demos/desktop-embedded/pluginhost.html#geplugin_browserok";*/

const NSString *PluginURL = @"file:///Users/richard/GoogleEarthSRTM/Test3.html#geplugin_browserok";
const NSString *kmlOutput = @"http://localhost/~richard/imagery/output2.kml";
const NSString *scalePath = @"/Users/richard/Sites/imagery/scale.png";

@implementation SampleController

@synthesize controlsEnabled;

// called when all objects in the nib (including the NSWindow) have loaded
- (void)awakeFromNib {
	// start with controls disabled
	[self setControlsEnabled:NO];
	
	// register a loading finished notification observer on the WebView
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(webViewFinishedLoading:)
												 name:WebViewProgressFinishedNotification
											   object:webView];
	
	// load the plugin page
	[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:(NSString *)PluginURL]]];	
	
	[myProgress setDisplayedWhenStopped:FALSE];
	
}

- (void)webViewFinishedLoading:(NSNotification *)notification {file://localhost/Users/richard/Sites/output.eps
	// set window.external as soon as the web view is done loading
	// the page
	
	// http://developer.apple.com/DOCUMENTATION/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html
	[[webView windowScriptObject] setValue:self forKey:@"external"];
}

- (IBAction)createPlacemark:(id)sender {
	// call a JS function, passing in the text field's value
	
	// http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/DisplayWebContent/Tasks/JavaScriptFromObjC.html
	
	NSLog(@"Drawing AOI");
	
	[[webView windowScriptObject] callWebScriptMethod:@"createGroundOverlay" withArguments:[NSArray arrayWithObjects:nil]];
}

- (void)JSAoiDrawnCallback:(NSString *)aoi {
	//this method calle after the user finishes drawing the AOI on the map
	
	[myProgress startAnimation:self];
	
	NSLog(@"AOI Drawn, getting SRTM");
	//NSLog(aoi);
		
	//convert the aoi string from JS to array of points
	NSArray *coords=[aoi componentsSeparatedByString:@","]; 
	
	//call get map script
	NSTask *mapTask=[[[NSTask alloc] init] autorelease];
	
	//set launch path (bash shell becuase running bash script)
	[mapTask setLaunchPath:@"/bin/bash"];
	
	//get shader settings
	NSString *shaderArgs = @"";
	if ([[curItem title] isEqualToString:@"Azimuth Shading"]) {
		NSLog(@"Run with azimuth shading");
		shaderArgs = @"-A315";
	} else if ([[curItem title] isEqualToString:@"dx Shading"]) {
		NSLog(@"Run with dx shading");
		shaderArgs = @"-A0";
	} else if ([[curItem title] isEqualToString:@"dy Shading"]) {
		NSLog(@"Run with dy shading");
		shaderArgs = @"-A270";
	} else {
		NSLog(@"No shading");
		shaderArgs = @"";
	}

	//set args (script to run followed by script args)
	[mapTask setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"subsetSRTM" ofType:@"sh"], 
						   [coords objectAtIndex:0],
						   [coords objectAtIndex:1], 
						   [coords objectAtIndex:2],
						   [coords objectAtIndex:3],
						   shaderArgs,
						   nil]];
	
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskFinished:) name:NSTaskDidTerminateNotification object:mapTask];
	[self setControlsEnabled:NO];
	
	//lauch the task and wait for it to finish before running loadKml in JS
	[mapTask launch];
	
	
	NSLog(@"Task launched!");
	
}

- (void) taskFinished:(NSNotification *)note {
	[myProgress stopAnimation:self];
	[self setControlsEnabled:YES];
	
	//get the KML and pass it to the JS method
	//NSString *kml = [NSString stringWithContentsOfFile:@"/Users/richard/SRTM15/output2.kml" encoding:NSUTF8StringEncoding error:NULL];	
	[[webView windowScriptObject] callWebScriptMethod:@"loadKml" withArguments:[NSArray arrayWithObjects:kmlOutput, nil]];
	
	NSImage *scaleImage = [[NSImage alloc] initWithContentsOfFile:scalePath]; 
	[scaleBox setImage:scaleImage];

}

- (IBAction)doOpen:(id)pId; {	
	NSLog(@"doOpen");	
	NSOpenPanel *tvarNSOpenPanelObj	= [NSOpenPanel openPanel];
	NSInteger tvarNSInteger	= [tvarNSOpenPanelObj runModalForTypes:[NSArray arrayWithObject:@"grd"]];
	if(tvarNSInteger == NSOKButton){
     	NSLog(@"doOpen we have an OK button");
		
		[myProgress startAnimation:self];
		
		NSString * tvarFilename = [tvarNSOpenPanelObj filename];
		NSLog(@"doOpen filename = %@",tvarFilename);
		
		NSTask *mapTask=[[[NSTask alloc] init] autorelease];
		
		//set launch path (bash shell becuase running bash script)
		[mapTask setLaunchPath:@"/bin/bash"];
		
		//get shader settings
		NSString *shaderArgs = @"";
		if ([[curItem title] isEqualToString:@"Azimuth Shading"]) {
			NSLog(@"Run with azimuth shading");
			shaderArgs = @"-A315";
		} else if ([[curItem title] isEqualToString:@"dx Shading"]) {
			NSLog(@"Run with dx shading");
			shaderArgs = @"-A0";
		} else if ([[curItem title] isEqualToString:@"dy Shading"]) {
			NSLog(@"Run with dy shading");
			shaderArgs = @"-A270";
		} else {
			NSLog(@"No shading");
			shaderArgs = @"";
		}
		
		//set args (script to run followed by script args)
		[mapTask setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"grd2kml" ofType:@"sh"],tvarFilename, shaderArgs, nil]];
				
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskFinished:) name:NSTaskDidTerminateNotification object:mapTask];
		[self setControlsEnabled:NO];

		//lauch the task and wait for it to finish before running loadKml in JS
		[mapTask launch];
		
		NSLog(@"Task launched!");
		
	} else if(tvarNSInteger == NSCancelButton) {
     	NSLog(@"doOpen we have a Cancel button");
     	return;
	} else {
     	NSLog(@"doOpen tvarInt not equal 1 or zero = %3d",tvarNSInteger);
     	return;
	} // end if     

} // end doOpen

- (IBAction)doSaveGrd:(id)pId; {	
	NSLog(@"doSave");	
	NSSavePanel *tvarNSSavePanelObj	= [NSSavePanel savePanel];
	NSInteger tvarNSInteger	= [tvarNSSavePanelObj runModal];
	if(tvarNSInteger == NSOKButton){
     	NSLog(@"doSave we have an OK button");
		
		NSString * tvarFilename = [tvarNSSavePanelObj filename];
		NSLog(@"doSave filename = %@",tvarFilename);
		
		NSTask *saveTask=[[[NSTask alloc] init] autorelease];
		
		//set launch path (bash shell becuase running bash script)
		[saveTask setLaunchPath:@"/bin/bash"];
		
		//set args (script to run followed by script args)
		[saveTask setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"savegrd" ofType:@"sh"], @"grd" ,tvarFilename, nil]];
		
		//lauch the task
		[saveTask launch];
				
		NSLog(@"Task launched!");	
		
	} else if(tvarNSInteger == NSCancelButton) {
     	NSLog(@"doSave we have a Cancel button");
     	return;
	} else {
     	NSLog(@"doSave tvarInt not equal 1 or zero = %3d",tvarNSInteger);
     	return;
	} // end if     
	
} // end doSaveGrd

- (IBAction)doSavePng:(id)pId; {	
	NSLog(@"doSave");	
	NSSavePanel *tvarNSSavePanelObj	= [NSSavePanel savePanel];
	NSInteger tvarNSInteger	= [tvarNSSavePanelObj runModal];
	if(tvarNSInteger == NSOKButton){
     	NSLog(@"doSave we have an OK button");
		
		NSString * tvarFilename = [tvarNSSavePanelObj filename];
		NSLog(@"doSave filename = %@",tvarFilename);
		
		NSTask *saveTask=[[[NSTask alloc] init] autorelease];
		
		//set launch path (bash shell becuase running bash script)
		[saveTask setLaunchPath:@"/bin/bash"];
		
		//set args (script to run followed by script args)
		[saveTask setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"savegrd" ofType:@"sh"], @"png" ,tvarFilename, nil]];
		
		//lauch the task
		[saveTask launch];
		
		NSLog(@"Task launched!");	
		
	} else if(tvarNSInteger == NSCancelButton) {
     	NSLog(@"doSave we have a Cancel button");
     	return;
	} else {
     	NSLog(@"doSave tvarInt not equal 1 or zero = %3d",tvarNSInteger);
     	return;
	} // end if     
	
} // end doSavePng


- (IBAction)doClearMap:(id)sender; {
	[[webView windowScriptObject] callWebScriptMethod:@"clearMap" withArguments:[NSArray arrayWithObjects:@"null", nil]];
}

- (void)JSInitSuccessCallback:(WebScriptObject *)ge {
	// WARNING: don't try to use ge here.. AFAIK, it won't work
	
	// turn on controls when the plugin is initialized
	[self setControlsEnabled:YES];
}

- (void)JSInitErrorCallback:(NSString *)errorString {
	// show an error message upon plugin failure
	NSAlert *alert = [NSAlert new];
	[alert setMessageText:[NSString stringWithFormat:@"Error: %@", errorString]];
	[alert runModal];
}

+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector {
	// expose the success and error callbacks
	if (aSelector == @selector(JSInitSuccessCallback:) ||
		aSelector == @selector(JSInitErrorCallback:) ||
		aSelector == @selector(JSAoiDrawnCallback:))
		return NO;
	
	return YES;
}

- (IBAction)selectShadingType:(id)sender; {
	NSLog(@"Select shading");
	[curItem setState:NSOffState]; 
	[sender setState:NSOnState];
	curItem = (NSMenuItem *)sender;
}

@end
