//
//  KeyboardSelector.m
//  Flash2
//
//  Created by Nicholas Matsakis on 10/17/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "KeyboardSelector.h"
#import "Ox.h"
#import "Language.h"
#import "Carbon/Carbon.h"
#import "OxNSArray.h"

@implementation KeyboardSelector

void logBindings(NSString *name, id object) {
	NSLog(@"%@ -----------------------------------------", name);
	for (id binding in [object exposedBindings]) {//[NSArray arrayWithObjects:@"value", @"content", @"selectedObject", nil]) {
		NSLog(@"attempting binding %@ of %@", binding, object);
		NSDictionary *bindingInfo = [object infoForBinding:binding];
		if (bindingInfo != nil) {
			for (id key in [bindingInfo allKeys])
				NSLog(@"  Key=%@ Value=%@", key, [bindingInfo objectForKey:key]);
		} else {
			NSLog(@"  not bound");
		}
	}
}

id boundObject(id object, id binding) {
	NSDictionary *bindingInfo = [object infoForBinding:binding];
	if (bindingInfo != nil) {
		id object = [bindingInfo valueForKey:NSObservedObjectKey];
		id keyPath = [bindingInfo valueForKey:NSObservedKeyPathKey];
		return [object valueForKeyPath:keyPath];
	}
	return nil;
}

- (BOOL)tableView:(NSTableView *)aTableView shouldEditTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	// Use the identifier of the column to guide which keyboard to use.
	/*
	NSDictionary *languageColumns = OxDict(@"fromCategory" FOR @"fromString", 
										   @"toCategory" FOR @"toString");
	NSString *categoryKey = [languageColumns objectForKey:[aTableColumn identifier]];
	if (categoryKey != nil) {
		NSTableColumn *relColumn = [aTableView tableColumnWithIdentifier:@"relation"];
		NSArray *relations = boundObject(relColumn, @"selectedObject");
		Relation *relation = [relations objectAtIndex:rowIndex];
		Category *category = [relation valueForKey:categoryKey];
		Language *language = category.language;
		TISInputSourceRef src = NULL;
		
		// HACKY: Improve
		if ([language.name isEqual:@"Greek"]) {
			NSArray *array = (NSArray*)TISCreateInputSourceList((CFDictionaryRef)OxDict(@"Greek" FOR kTISPropertyLocalizedName), false);
			if (![array isEmpty])
				src = (TISInputSourceRef)[array _0];
		} else {
			src = TISCopyInputSourceForLanguage((CFStringRef)@"en");
		}
		
		if (src != NULL) {
			TISSelectInputSource(src);
		}
	}
	 */
	return YES;
}

@end
