//
//  MainController.m
//  VH7PC_Controller
//
//  Created by NYA on Wed Jul 09 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import "MainController.h"
#import "DirectController.h"
#import "VH7PC.h"
#import "CHAppleScript.h"
#import "Preferences.h"
#import "DirectController.h"
#import "Recoder.h"


@interface NSPanel(Activate)
- (void) activateAndMakeKey:(id)sender;
@end
@implementation NSPanel(Activate)
- (void) activateAndMakeKey:(id)sender {
	[NSApp activateIgnoringOtherApps:YES];
	[self makeKeyAndOrderFront:sender];
}
@end

@implementation MainController

-(id)init{
    [super init];
    
    _sbItemShowing=YES;
	//recoder_ = [[Recoder alloc] init];
	
    NSDistributedNotificationCenter *nc;
    nc=[NSDistributedNotificationCenter notificationCenterForType:NSLocalNotificationCenterType];
    [nc addObserver:self selector:@selector(addVH7PC) name:@"CHVH7PCAdded" object:nil];
    [nc addObserver:self selector:@selector(removeVH7PC) name:@"CHVH7PCRemoved" object:nil];
    [nc addObserver:self selector:@selector(systemWillSleep) name:@"CHVH7PCSystemWillSleep" object:nil];
    [nc addObserver:self selector:@selector(systemHasPoweredOn) name:@"CHVH7PCSystemHasPoweredOn" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setMenuImage:) name:@"MenuImageUpdateNotification" object:nil];
    return self;
}

-(void)awakeFromNib{
    NSStatusBar *bar=[NSStatusBar systemStatusBar];

    notifireInit();
    _sbItem=[bar statusItemWithLength:NSVariableStatusItemLength];
    [_sbItem retain];
    [_sbItem setTitle:@""];
    [_sbItem setToolTip:@"VH7PC Controller"];
    [_sbItem setHighlightMode:YES];
    [_sbItem setImage:[NSImage imageNamed:@"menuicon_removed.png"]];
    [_sbItem setMenu:_notfoundMenu];
}

-(void)systemHasPoweredOn{
    if([_prefs autoPower]){
        if([_vh7pc getStatus]==0)
            if(![_vh7pc statusRef]->powerOn) [_directCtrl power:nil];
    }
}

-(void)systemWillSleep{
    if([_prefs autoPower]){
        if([_vh7pc getStatus]==0)
            if([_vh7pc statusRef]->powerOn) [_directCtrl power:nil];
    }
    allowPowerChange();
}

-(void)addVH7PC{
    grabDevice();
    [_vh7pc setConnedted:YES];
    if(_sbItemShowing){
        [_sbItem setMenu:_vh7pcMenu];
    	[self updateMenu];
    }
    if([_prefs autoPower]){
        if([_vh7pc getStatus]==0)
            if([_vh7pc statusRef]->powerOn==NO) [_directCtrl power:nil];
    }
    //NSLog(@"VH7PC added.");
}

-(void)removeVH7PC{
    releaseDevice();
    [_vh7pc setConnedted:NO];
    if(_sbItemShowing){
        [_sbItem setImage:[NSImage imageNamed:@"menuicon_removed.png"]];
        [_sbItem setMenu:_notfoundMenu];
    }
    //NSLog(@"VH7PC removed.");
}

-(void)setMenuImage:(BOOL)b{
	if(_sbItemShowing) {
		[_sbItem setImage:[NSImage imageNamed:(b?@"menuicon_on.tif":@"menuicon_off.tif")]];
		if ([(Recoder *)recoder_ status] != REC_IDLE) {
			if ([(Recoder *)recoder_ status] == REC_RECORD) 
				[_sbItem setImage:[NSImage imageNamed:@"menuicon_rec.tif"]];
			else if ([(Recoder *)recoder_ status] == REC_THROUGH) 
				[_sbItem setImage:[NSImage imageNamed:@"menuicon_through.tif"]];
		}
	}
}

-(void)updateMenu{
    id tmp;
    BOOL err;
    VH7PC_stat *status;
	
	menuItemsCount_ = 0;
	
	menuItemsCount_ = 6;
    
    [self removeItems:_vh7pcMenu withRange:NSMakeRange(6,[_vh7pcMenu numberOfItems]-6)];
    err=[_vh7pc getStatus];
    status=[_vh7pc statusRef];
    /*
    if(err){
        [_sbItem setImage:[NSImage imageNamed:@"menuicon_off.tif"]];
        [_vh7pcMenu addItem:[NSMenuItem separatorItem]];
        [_vh7pcMenu addItemWithTitle:@"VH7PC is not found!!!" action:@selector(quit:) keyEquivalent:@""];
        [_vh7pcMenu addItem:[NSMenuItem separatorItem]];
        tmp=[_vh7pcMenu addItemWithTitle:@"About..." action:@selector(orderFront:) keyEquivalent:@""];
        [tmp setTarget:_aboutPanel];
        tmp=[_vh7pcMenu addItemWithTitle:@"HotKeys..." action:@selector(orderFront:) keyEquivalent:@""];
        [tmp setTarget:_hotkeyPanel];
        tmp=[_vh7pcMenu addItemWithTitle:@"Quit" action:@selector(quit:) keyEquivalent:@""];
        [tmp setTarget:self];
        NSLog(@"VH7PC is not found!!!");
        return;
    }
    */
    [self setMenuImage:status->powerOn];
    
    [[_vh7pcMenu itemWithTag:powerM] 
		setTitle:[[NSBundle mainBundle] localizedStringForKey:(status->powerOn?@"Power off":@"Power on") value:nil table:nil]];
    [[_vh7pcMenu itemWithTag:volumeM] 
		setTitle:[NSString stringWithFormat:[[NSBundle mainBundle] localizedStringForKey:@"Volume:%d" value:nil table:nil], status->volume]];
    [[_vh7pcMenu itemWithTag:muteM] setState:(status->mute?NSOnState:NSOffState)];
    switch(status->tone){
        case TONE:	[[_vh7pcMenu itemWithTag:toneM] 
			setTitle:[[NSBundle mainBundle] localizedStringForKey:@"Tone:[TONE]" value:nil table:nil]];	break;
        case NB1:	[[_vh7pcMenu itemWithTag:toneM] 
			setTitle:[[NSBundle mainBundle] localizedStringForKey:@"Tone:[N.B.1]" value:nil table:nil]];	break;
        case NB2:	[[_vh7pcMenu itemWithTag:toneM] 
			setTitle:[[NSBundle mainBundle] localizedStringForKey:@"Tone:[N.B.2]" value:nil table:nil]];	break;
        default:	[[_vh7pcMenu itemWithTag:toneM] 
			setTitle:[[NSBundle mainBundle] localizedStringForKey:@"Tone" value:nil table:nil]];
    }
    [self setOffState:[[_vh7pcMenu itemWithTag:inputM] submenu]];
    [_vh7pcMenu addItem:tmp=[NSMenuItem separatorItem]];
    switch(status->inputMode){
        case CD:
            [[[[_vh7pcMenu itemWithTag:inputM] submenu] itemWithTag:cdM] setState:NSOnState];
            [self inlineSubmenu:_cdMenu inMenu:_vh7pcMenu];
            break;
        case MD:
            [[[[_vh7pcMenu itemWithTag:inputM] submenu] itemWithTag:mdM] setState:NSOnState];
            [self inlineSubmenu:_mdMenu inMenu:_vh7pcMenu];
            break;
        case AM:
            [[[[_vh7pcMenu itemWithTag:inputM] submenu] itemWithTag:amM] setState:NSOnState];
            [self inlineSubmenu:_bandMenu inMenu:_vh7pcMenu];
            [[_vh7pcMenu itemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"Auto mono" value:nil table:nil]] setState:(status->atAuto?NSOnState:NSOffState)];
            [[_vh7pcMenu itemWithTitle:@"Band"] setTitle:
                [NSString stringWithFormat:[[NSBundle mainBundle] localizedStringForKey:@"[AM:%d%@kHz]" value:nil table:nil],
                status->rStationNum_U,[self decimal2Str:status->rStationNum_D]]];
            break;
        case FM:
            [[[[_vh7pcMenu itemWithTag:inputM] submenu] itemWithTag:fmM] setState:NSOnState];
            [self inlineSubmenu:_bandMenu inMenu:_vh7pcMenu];
            [[_vh7pcMenu itemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"Auto mono" value:nil table:nil]] setState:(status->atAuto?NSOnState:NSOffState)];
            [[_vh7pcMenu itemWithTitle:@"Band"] setTitle:
                [NSString stringWithFormat:[[NSBundle mainBundle] localizedStringForKey:@"[FM:%d.%@MHz]" value:nil table:nil],status->rStationNum_U,
                [self decimal2Str:status->rStationNum_D]]];
            break;
        case TAPE:
            [[[[_vh7pcMenu itemWithTag:inputM] submenu] itemWithTag:tapeM] setState:NSOnState];
            [self inlineSubmenu:_tapeMenu inMenu:_vh7pcMenu];
            break;
        default:
            [[[[_vh7pcMenu itemWithTag:inputM] submenu] itemWithTag:usbM] setState:NSOnState];
            [_vh7pcMenu removeItem:tmp];
    }

    [_vh7pcMenu addItem:[NSMenuItem separatorItem]];
	
	//録音関係
    tmp=[_vh7pcMenu addItemWithTitle:[recoder_ throughMenuString] action:@selector(playThrough) keyEquivalent:@""];
    [tmp setTarget:recoder_];
    tmp=[_vh7pcMenu addItemWithTitle:[recoder_ recordMenuString] action:@selector(record) keyEquivalent:@""];
    [tmp setTarget:recoder_];
    tmp=[_vh7pcMenu 
		addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"Air Check..." value:nil table:nil]
		action:@selector(activateAndMakeKey:) 
		keyEquivalent:@""];
    [tmp setTarget:reservationPanel_];
    //tmp=[_vh7pcMenu addItemWithTitle:@"Record Setting..." action:@selector(setting) keyEquivalent:@""];
    //[tmp setTarget:recoder_];
	menuItemsCount_ += 4;
	
    [_vh7pcMenu addItem:[NSMenuItem separatorItem]];
	menuItemsCount_ += 1;

    tmp=[_vh7pcMenu 
		addItemWithTitle:[[NSBundle mainBundle] 
			localizedStringForKey:([_directCtrl controllerShowed]?@"Hide controller":@"Show controller") value:nil table:nil]
        action:@selector(triggerController:) 
		keyEquivalent:@""];
    [tmp setTarget:_directCtrl];
    tmp=[_vh7pcMenu 
		addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"About..." value:nil table:nil] 
		action:@selector(activateAndMakeKey:) 
		keyEquivalent:@""];
    [tmp setTarget:_aboutPanel];
    tmp=[_vh7pcMenu 
		addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"HotKeys..." value:nil table:nil]
		action:@selector(activateAndMakeKey:) 
		keyEquivalent:@""];
    [tmp setTarget:_hotkeyPanel];
    tmp=[_vh7pcMenu 
		addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"Preferences..." value:nil table:nil]
		action:@selector(activateAndMakeKey:) 
		keyEquivalent:@""];
    [tmp setTarget:_prefPanel];

    [_vh7pcMenu addItem:[NSMenuItem separatorItem]];
	menuItemsCount_ += 1;

    tmp=[_vh7pcMenu 
		addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"Quit" value:nil table:nil]
		action:@selector(quit:) 
		keyEquivalent:@""];
    [tmp setTarget:self];
	menuItemsCount_ += 5;
}

-(void)inlineSubmenu:(NSMenu *)sm inMenu:(NSMenu *)mm{
    NSEnumerator *enu=[[sm itemArray] objectEnumerator];
    id obj;
    
    while(obj=[enu nextObject])
        [mm addItem:[[obj copy] autorelease]];
}

-(void)removeAllItems:(NSMenu *)menu{
    while([menu numberOfItems])
        [menu removeItemAtIndex:0];
}

-(void)removeItems:(NSMenu *)menu withRange:(NSRange)r{
    int i;
    
    for(i=0;i<r.length;i++){
        if([menu numberOfItems]<r.location) return;
        [menu removeItemAtIndex:r.location];
    }
}

-(void)setOffState:(NSMenu *)m{
    NSEnumerator *enu=[[m itemArray] objectEnumerator];
    id obj;
    
    while(obj=[enu nextObject])
        [obj setState:NSOffState];
}

-(NSString *)decimal2Str:(int)i{
    if(i<10) return [NSString stringWithFormat:@"0%1d",i];
    else return [NSString stringWithFormat:@"%1d",i];
}

-(BOOL)sbItemShowing{
    return _sbItemShowing;
}

-(void)menuItemTrigger{
    NSStatusBar *bar=[NSStatusBar systemStatusBar];
    NSUserDefaults *defaults=[ NSUserDefaults standardUserDefaults ];
    if(_sbItemShowing){
        _sbItemShowing=NO;
        [bar removeStatusItem:_sbItem];
        [_sbItem release];
    }else{
        _sbItemShowing=YES;
        _sbItem=[bar statusItemWithLength:NSVariableStatusItemLength];
        [_sbItem retain];
        [_sbItem setTitle:@""];
        [_sbItem setToolTip:@"VH7PC Controller"];
        [_sbItem setHighlightMode:YES];
        if(![_vh7pc connected]) [_sbItem setImage:[NSImage imageNamed:@"menuicon_removed.png"]];
        else{
            [_vh7pc getStatus];
            [self setMenuImage:[_vh7pc statusRef]->powerOn];
        }
        if([_vh7pc connected]) [_sbItem setMenu:_vh7pcMenu];
        else [_sbItem setMenu:_notfoundMenu];
    }
    [defaults setObject:[NSNumber numberWithBool:_sbItemShowing] forKey:@"StatusItemVisible"];
    [defaults synchronize];
}

-(IBAction)goHome:(id)sender{
    [CHAppleScript openURL:@"http://cathand.org/"];
}

-(IBAction)quit:(id)sender{
    [NSApp terminate:self];
}

-(void)dealloc{
    NSDistributedNotificationCenter *nc;
    
	//[recoder_ release];
    nc=[NSDistributedNotificationCenter notificationCenterForType:NSLocalNotificationCenterType];
    [nc removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if(_sbItemShowing){
        [[NSStatusBar systemStatusBar] removeStatusItem:_sbItem];
        [_sbItem release];
    }
    [super dealloc];
}

- (int)numberOfItemsInMenu:(NSMenu *)menu {
   //NSLog(@"numberOfItemsInMenu");
   [self updateMenu];
   
   return [menu numberOfItems];
}

- (BOOL)menu:(NSMenu *)menu updateItem:(NSMenuItem *)item atIndex:(int)index shouldCancel:(BOOL)shouldCancel {
   //NSLog(@"update");
   //[self updateMenu];
   
   return YES;
}


- (IBAction) recordSetting:(id) sender {
	[recoder_ setting];
}

@end
