//
//  X10RemoteController.m
//  X10Remote
//
//  Created by Nicholas Riley on Sat Jan 24 2004.
//  Copyright (c) 2004 Nicholas Riley. All rights reserved.
//

#import "X10RemoteController.h"
#import "NJRHotKey.h"
#import "NJRHotKeyManager.h"
#import "NJRWindowMagnetism.h"

@implementation X10RemoteController

- (void)_launchRemoteShellTask;
{
    NSLog(@"Attempting to connect to stripped");
    [remoteShellTask release];
    remoteShellTask = [[NSTask alloc] init];
    [remoteShellTask setLaunchPath: @"/bin/zsh"];
    [remoteShellTask setArguments: [NSArray arrayWithObjects: @"-c", @"ssh stripped /bin/sh", nil]];
    NSPipe *remoteShellPipe = [NSPipe pipe];
    [remoteShellTask setStandardInput: remoteShellPipe];
    remoteShellInput = [remoteShellPipe fileHandleForWriting];
    [remoteShellTask launch];
    [remoteShellInput writeData: [NSData data]];
}

- (void)_toggleVisible:(id)sender;
{
    NSWindow *window = [self window];
    if ([window isVisible]) {
        if ([window isKeyWindow])
            [NSApp hide: self];
        [window orderOut: self];
    } else {
        [NSApp activateIgnoringOtherApps: YES];
        [window makeKeyAndOrderFront: self];
    }
}
                        
- (void)awakeFromNib;
{
    NJRHotKeyManager *hotKeyManager = [NJRHotKeyManager sharedManager];
    NSWindow *window = [self window];
    [hotKeyManager addShortcutWithIdentifier: @"X10RemoteControllerToggleVisible"
                                      hotKey: [NJRHotKey hotKeyWithCharacters: @"x"
                                                                modifierFlags: NSCommandKeyMask | NSControlKeyMask
                                                                      keyCode: 7]
                                      target: self
                                      action: @selector(_toggleVisible:)];
    [self _launchRemoteShellTask];
    [window setHidesOnDeactivate: NO];
    [[NJRWindowMagnetism alloc] initForWindow: window];
}

- (void)_sendToRemote:(NSString *)commandString;
{
    NSData *commandData = [commandString dataUsingEncoding: NSASCIIStringEncoding];
    if (![remoteShellTask isRunning])
        [self _launchRemoteShellTask];
    [remoteShellInput writeData: commandData];
    if (![remoteShellTask isRunning]) {
        [self _launchRemoteShellTask];
        [remoteShellInput writeData: commandData];
    }
}

- (IBAction)turnUnitOn:(NSButton *)sender;
{
    [self _sendToRemote: [NSString stringWithFormat: @"br n%d on\n", [sender tag]]];
}

- (IBAction)turnUnitOff:(NSButton *)sender;
{
    [self _sendToRemote: [NSString stringWithFormat: @"br n%d off\n", [sender tag]]];
}

@end
