//
// HotKeyApplication.m
//

#import "HotkeyApp.h"
#import "VH7PC.h"
#import "Recoder.h"


@implementation HotkeyApp

static NSMutableDictionary*	_targetDict = nil;

- (id)init
{
    self = [super init];
    if (self) {
        _targetDict = [[NSMutableDictionary dictionary] retain];
    }
    
    return self;
}

//
// Event handling
//

// Undocumented event subtype
enum {
    kEventHotKeyPressedSubtype = 6, 
    kEventHotKeyReleasedSubtype = 9, 
};

- (void)sendEvent:(NSEvent*)event
{
    // For hot key event
    if ([event type] == NSSystemDefined && 
        [event subtype] == kEventHotKeyPressedSubtype)
    {
        EventHotKeyRef	hotKeyRef;
        NSData*			data;
        
        // Get hot key refrence
        hotKeyRef = (EventHotKeyRef)[event data1];
        
        // Get object and selector
        data = (NSData*)[_targetDict objectForKey:[NSNumber numberWithInt:(int)hotKeyRef]];
        if (data) {
            int	buf[2];
            id	object;
            SEL	selector;
            
            [data getBytes:buf length:sizeof(buf)];
            object = (id)buf[0];
            selector = (SEL)buf[1];
            if (object && selector) {
                [object performSelector:selector];
            }
        }
    }
    
    [super sendEvent:event];
}

//
// Register hot key
//

- (void*)registerHotKeyCode:(unsigned int)keyCode 
                withModifier:(unsigned int)keyModifier 
                target:(id)object 
                selector:(SEL)selector
{
    static UInt32	_id = 0;
    
    OSStatus		status;
    UInt32			modifier;
    EventHotKeyID	keyId;
    EventHotKeyRef	hotKeyRef;
    int				buf[2];
    
    // Make key modifier
    modifier = 0;
    if (keyModifier & NSShiftKeyMask) { modifier |= shiftKey; }
    if (keyModifier & NSControlKeyMask) { modifier |= controlKey; }
    if (keyModifier & NSCommandKeyMask) { modifier |= cmdKey; }
    if (keyModifier & NSAlternateKeyMask) { modifier |= optionKey; }
    
    // Make hot key ID
    keyId.signature = 'CHcs';//'HtKe';
    keyId.id = _id++;
    
    // Register hot key
    status = RegisterEventHotKey(
                    keyCode, 
                    modifier, 
                    keyId, 
                    GetApplicationEventTarget(), 
                    0, 
                    &hotKeyRef);
    if (status != noErr) {
        return NULL;
    }
    
    // Set hot key reference into dictionary
    buf[0] = (int)object;
    buf[1] = (int)selector;
    [_targetDict setObject:[NSData dataWithBytes:buf length:sizeof(buf)] 
                    forKey:[NSNumber numberWithInt:(int)hotKeyRef]];
    
    return (void*)hotKeyRef;
}

- (void)unregisterHotKey:(void*)hotKeyRef
{
    OSStatus	status;
    
    // Unregister hot key
    status = UnregisterEventHotKey(hotKeyRef);
    
    // Remove hot key reference from dictionary
    [_targetDict removeObjectForKey:[NSNumber numberWithInt:(int)hotKeyRef]];
}


-(NSNumber *)command{
    return [NSNumber numberWithInt:command];
}

-(NSNumber *)value{
    return [NSNumber numberWithInt:value];
}

-(void)setCommand:(NSNumber *)sender{
    command=[sender intValue];
}

-(void)setValue:(NSNumber *)sender{
    value=[sender intValue];
}

-(id)handleSendCommand:(NSScriptCommand *)s{
    if(command==GET_STATUS) [vh7pc getStatus];
    else [vh7pc sendCommand:command andValue:value];
    return nil;
}

-(id)handleGetStatus:(NSScriptCommand *)s{
    VH7PC_stat *stat=[vh7pc statusRef];
    return [NSDictionary dictionaryWithObjectsAndKeys:
            [NSNumber numberWithBool:stat->powerOn],@"PowerOn",
            [NSNumber numberWithBool:stat->mute],@"Mute",
            [NSNumber numberWithInt:stat->tone],@"Tone",
            [NSNumber numberWithInt:stat->inputMode],@"InputMode",
            [NSNumber numberWithInt:stat->rPresetNum],@"RadioPresetNumber",
            [NSNumber numberWithInt:stat->rStationNum_U],@"RadioStationNumberUpper",
            [NSNumber numberWithInt:stat->rStationNum_D],@"RadioStationNumberLower",
            [NSNumber numberWithInt:stat->cdTracknum],@"CDTrackNumber",
            [NSNumber numberWithInt:stat->cdMin],@"CDMinute",
            [NSNumber numberWithInt:stat->cdSec],@"CDSecond",
            [NSNumber numberWithInt:stat->cdMaxTrack],@"CDMaxTrack",
            [NSNumber numberWithInt:stat->repInfo],@"RepeatInformation",
            [NSNumber numberWithInt:stat->volume],@"Volume",
            [NSNumber numberWithBool:stat->atAuto],@"AtAuto",
            nil];
}

-(id)handleRecordTrigger:(NSScriptCommand *)s {
	[recoder_ record];
	return nil;
}

@end
