/*******************************************************************************
 Copyright (c) 2005-2006 Jordy Rose
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 
 Except as contained in this notice, the name(s) of the above copyright holders
 shall not be used in advertising or otherwise to promote the sale, use or other
 dealings in this Software without prior authorization.
*******************************************************************************/

//
//  DockyardPlugin.m
//  Dockyard
//
#import "DockyardPlugin.h"

NSArray *emptyArray = nil;

/*!
 * Central class for the Dockyard Widget Plugin. DockyardPlugin sets up the preferences instance,
 * controls the list of docks on the reverse side of the widget, and is responsible for the 
 * rename, delete, and create actions, as well as providing a beep effect for JavaScript to use.
 *
 * @version 1.0
 * @author Belkadan Software
 */
@implementation DockyardPlugin
- (id)initWithWebView:(WebView *)newWebView
{
	if (self = [super init]) {
		preferences = [[DockyardPreferences alloc] initWithIdentifier:@"com.belkadan.Dockyard.Widget"];
		[preferences setDelegate:self];
		webView = newWebView;
	}
	return self;
}

- (void)dealloc
{
	[preferences release];
	[super dealloc];
}

/*!
 * When this method is called, DockyardPlugin makes both itself and its instance of
 * DockyardPreferences available in JavaScript.
 */
- (void)windowScriptObjectAvailable:(WebScriptObject *)windowScriptObject
{
	scriptObject = windowScriptObject;
	[windowScriptObject setValue:preferences forKey:@"dockyardPrefs"];
	[windowScriptObject setValue:self forKey:@"dockyardPlugin"];
}

/*!
 * Forwards the message to the widget to inform it that the list of docks needs updating.
 */
- (void)updateTables
{
	[scriptObject callWebScriptMethod:@"updateTables" withArguments:emptyArray];
}

#pragma mark -

- (void)dockyardDockChanged:(NSNotification *)note
{
	NSDictionary *info = [note userInfo];
	NSString *newDock = [info objectForKey:@"newDock"];
	
	[scriptObject evaluateWebScript:[NSString stringWithFormat:@"currentDock = %@; moveSelectionToTag(currentDock);", newDock]];
}

- (void)dockyardDockCreated:(NSNotification *)note
{
	[self updateTables];
}

- (void)dockyardDockRenamed:(NSNotification *)note
{
	[self updateTables];
}

- (void)dockyardDocksReordered:(NSNotification *)note
{
	[self updateTables];
}

- (void)dockyardDockDeleted:(NSNotification *)note
{
	[self updateTables];
}

- (void)dockyardDocksDeleted:(NSNotification *)note
{
	[self updateTables];
}

- (void)dockyardDashboardSwitchChanged:(NSNotification *)note
{
	[scriptObject evaluateWebScript:[NSString stringWithFormat:@"document.getElementById('shouldSwitchDashboard').checked = %@",
		([[[note userInfo] objectForKey:@"shouldSwitchDashboard"] boolValue]) ? @"true" : @"false"]];
}

#pragma mark -

/*!
 * Changes Objective-C selectors into JavaScript method names: <code>deleteDocks:</code>
 * becomes <code>deleteDocks</code> (no colon), and <code>createDockWithName:dockTemplate:dashboardTemplate:</code>
 * becomes <code>createDockWithNameAndFiles</code>.
 */
+ (NSString *)webScriptNameForSelector:(SEL)sel
{
	if (sel == @selector(deleteDocks:))
		return @"deleteDocks";
	else if (sel == @selector(createDockWithName:dockTemplate:dashboardTemplate:))
		return @"createDockWithNameAndFiles";
	else
		return nil;
}

/*!
 * Limits the widget to seven methods: <code>showBackSide</code>, <code>hideBackSide</code>,
 * <code>deleteDocks</code>, <code>createDockWithName:dockTemplate:dashboardTemplate:</code>,
 * and <code>beep</code>.
 *
 * @see DockyardPreferences+WebKitAdditions#isSelectorExcludedFromWebScript:
 */
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)sel
{
	return !(
				sel == @selector(showBackSide)	||
				sel == @selector(hideBackSide)	||
				sel == @selector(deleteDocks:)	||
				sel == @selector(createDockWithName:dockTemplate:dashboardTemplate:)	||
				sel == @selector(beep)
			);
}

/*!
 * Forbids the widget from accessing any properties.
 */
+ (BOOL)isKeyExcludedFromWebScript:(SEL)sel
{
	return YES;
}

/*!
 * Expose NSBeep functionality to JavaScript.
 */
- (void)beep
{
	NSBeep();
}

/*!
 * Called when the widget shows the back side. Unhides the table of docks.
 */
- (void)showBackSide
{
	[backSideView setHidden:NO];
}

/*!
 * Called when the widget hides the back side. Hides the table of docks.
 */
- (void)hideBackSide
{
	[backSideView setHidden:YES];
}

/*!
 * Called by the widget when the user clicks the "delete" button. Fetches the selected
 * docks, then calls <code>deleteDocksAtIndexes:</code> on DockyardPreferences.
 */
- (void)deleteDocks:(WebScriptObject *)javascriptIndexArray
{
	NSArray *indexArray = [[NSArray alloc] initWithArray:(NSArray *)javascriptIndexArray];
	NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndexesInArray:indexArray];
	unsigned index = [[preferences dockNames] indexOfObject:[preferences currentDock]];
	
	if ([preferences deleteDocksAtIndexes:indexSet]) {
		if ([indexSet containsIndex:index])
			[scriptObject callWebScriptMethod:@"changeToFirstDock" withArguments:emptyArray];
		[self updateTables];
	} else
		NSBeep();
	
	[indexArray release];
	[indexSet release];
}

/*!
 * Called by the widget when the user clicks the "create" button. First matches up the given
 * template names with the dock files, then calls <code>createDockWithName:fromFile:dashboardFile:</code>
 * on DockyardPreferences.
 */
- (void)createDockWithName:(NSString *)name dockTemplate:(NSString *)dockTemplate dashboardTemplate:(NSString *)dashboardTemplate
{
	static NSString *appleDockPath = nil;
	static NSString *emptyDockPath = nil;
	static NSString *currentDockPath = nil;

	static NSString *appleDashboardPath = nil;
	static NSString *emptyDashboardPath = nil;
	static NSString *currentDashboardPath = nil;
	
	NSString *dockPath, *dashboardPath;

	switch ([dockTemplate characterAtIndex:0]) {
	case 'a': // Apple
		if (appleDockPath == nil)
			appleDockPath = [[[NSBundle bundleWithPath:@"/System/Library/CoreServices/Dock.app"] pathForResource:@"default" ofType:@"plist"] retain];
		dockPath = appleDockPath;
		break;
	case 'e': // Empty dock
		if (emptyDockPath == nil)
			emptyDockPath = [[[NSBundle bundleForClass:[self class]] pathForResource:@"emptyDock" ofType:@"plist"] retain];
		dockPath = emptyDockPath;
		break;
	case 'c':
	default: // Default to same as current
		if (currentDockPath == nil)
			currentDockPath = [[@"~/Library/Preferences/com.apple.dock.plist" stringByStandardizingPath] retain];
		dockPath = currentDockPath;
	}
	
	switch ([dashboardTemplate characterAtIndex:0]) {
	case 'a': // Apple dashboard -- location unknown
		if (appleDashboardPath == nil)
			appleDashboardPath = [[[NSBundle bundleForClass:[self class]] pathForResource:@"defaultDashboard" ofType:@"plist"] retain];
		dashboardPath = appleDashboardPath;
		break;
	case 'e': // Empty dashboard
		if (emptyDashboardPath == nil)
			emptyDashboardPath = [[[NSBundle bundleForClass:[self class]] pathForResource:@"emptyDashboard" ofType:@"plist"] retain];
		dashboardPath = emptyDashboardPath;
		break;
	case 'c':
	default: // Default to same as current
		if (currentDashboardPath == nil)
			currentDashboardPath = [[@"~/Library/Preferences/com.apple.dashboard.plist" stringByStandardizingPath] retain];
		dashboardPath = currentDashboardPath;
	}
		
	if ([preferences createDockWithName:name fromFile:dockPath dashboardFile:dashboardPath]) {
		[self updateTables];
	} else {
		NSBeep();
	}
}

@end
