#import "ControllerController.h"
#import "ControllerView.h"
#import "VH7PC.h"
#import "DummyClass.h"
#import "DirectController.h"
#import "ControllerButton.h"


@implementation ControllerController
NSTimer *refleshTimer=nil;

-(id)init{
    [super init];
    return self;
}
/*
-(void)awakeFromNib{
    [self setSkin:[[NSBundle mainBundle] pathForResource:@"default" ofType:@"vh7skn"]];
}*/

-(id)skinPath{
    return _skinPath;
}

-(void)setSkinFromPref:(NSString*)s{
    if(s) [self setSkin:s];
    else{
        [self setSkin:[[NSBundle mainBundle] pathForResource:@"default" ofType:@"vh7skn"]];
        [_skinPath release];
        _skinPath=nil;
    }
}
/*
-(void)setPrefsWithDictionary:(NSDictionary *)d{
    id tmp=nil;
    if(tmp=[d objectForKey:@"SkinPath"]) [self setSkin:tmp];
    else{
        [self setSkin:[[NSBundle mainBundle] pathForResource:@"default" ofType:@"vh7skn"]];
        [_skinPath release];
        _skinPath=nil;
    }
}
*/
/*
-(void)setExceptSkinPrefsWithDictionary:(NSDictionary *)d{
    id tmp=nil;
    if(tmp=[d objectForKey:@"ShowAtLaunch"]) [self setShowAtL:tmp];
    else{
        [self setSkin:[[NSBundle mainBundle] pathForResource:@"default" ofType:@"vh7skn"]];
        [_skinPath release];
        _skinPath=nil;
    }
}
*/

-(void)startTimer{
    refleshTimer = [ NSTimer scheduledTimerWithTimeInterval 
                             : 1.0 
                      target : self 
                    selector : @selector(displayStatus) 
                    userInfo : nil
                     repeats : YES ];
}

-(void)endTimer{
    [refleshTimer invalidate];
}

-(void)setSkin:(NSString*)path{
    int i;
    id obj=nil;
    [_skinPath release];
    _skinPath=[path copy];
    ControllerSkin* skin=[ControllerSkin skinWithPath:_skinPath];
    
    if(!(obj=[skin backgroundImage])) return;
    [[_view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    NSRect r;
    r.origin=[[_view window] frame].origin;
    r.size=[obj size];
    [[_view window] setFrame:r display:NO];
    [_view setImage:obj];
    
    [_skinNameField setStringValue:[skin name]];
    
    for(i=0;i<DISPLAY_ITEM_NUM;i++){
        NSPoint p;
        obj=[skin displayImageForTag:i andOrigin:&p];
        if(obj) [_view setDisplayImage:obj andOrigin:p forTag:i];
    }
    
    /*
    for(i=0;i<DISPLAY_TEXT_NUM;i++){
        obj=[skin displayTextFieldForTag:i];
        if(obj) [_view addSubview:(_displayField[i]=obj)];
    }
    */
    for(i=0;i<DISPLAY_TEXT_NUM;i++){
        NSRect r;
        obj=[skin displayTextForTag:i inRect:&r];
        if(obj) [_view setDisplayHtml:obj andRect:r forTag:i];
    }
        
    obj=[skin volumeSlider];
    [obj setTarget:self];
    [obj setAction:@selector(performSlider:)];
    [_view addSubview:obj];
    _volumeSlider=obj;
    
    for(i=0;i<BUTTON_NUM;i++){
        obj=[skin buttonForTag:i];
        if(!obj) continue;
        [obj setTarget:self];
        [obj setAction:@selector(performButton:)];
        if(i==fb_b||i==ff_b){
            [obj setDownTarget:self];
            [obj setDownAction:@selector(performButtonDn:)];
        }
        [_view addSubview:obj];
        if(i<5) _inputButton[i]=obj;
    }
    
    [self displayStatus];
    [_view display];
    [[_view window] invalidateShadow];
    [[_view window] setHasShadow:YES];
}

-(IBAction)openSkin:(id)sender{
    NSOpenPanel *opFile=[NSOpenPanel openPanel];
    int tmp;

    tmp=[opFile runModalForTypes:[NSArray arrayWithObject:@"vh7skn"]];
    if(tmp==NSOKButton){
        [self setSkin:[opFile filename]];
    }
}

-(void)displayStatus{
    [_vh7pc getStatus];
    [_view setAllDisplayItem:NO];
    if([_vh7pc statusRef]->powerOn){
        switch([_vh7pc statusRef]->inputMode){
            case PC_USB:
                [_view setDisplayText:@"PC USB" forTag:input_text];
                [_view setDisplayText:@"" forTag:number_text];
                break;
            case AM:
                [_view setDisplayText:
                    ([_vh7pc statusRef]->rPresetNum?[NSString stringWithFormat:@"%@%d",@"AM: ",
                        [_vh7pc statusRef]->rPresetNum]:@"AM")
                    forTag:input_text];
                [_view setDisplayText:
                    [NSString stringWithFormat:@"%d%@ %@",
                        [_vh7pc statusRef]->rStationNum_U,
                        [self decimal2Str:[_vh7pc statusRef]->rStationNum_D],
                        @"kHz"]
                    forTag:number_text];
                if([_vh7pc statusRef]->atAuto) [_view setDisplayItemDisplay:YES forTag:automono];
                break;
            case FM:
                [_view setDisplayText:
                    ([_vh7pc statusRef]->rPresetNum?[NSString stringWithFormat:@"%@%d",@"FM: ",
                        [_vh7pc statusRef]->rPresetNum]:@"FM")
                    forTag:input_text];
                [_view setDisplayText:
                    [NSString stringWithFormat:@"%d.%@ %@",
                        [_vh7pc statusRef]->rStationNum_U,
                        [self decimal2Str:[_vh7pc statusRef]->rStationNum_D],
                        @"MHz"]
                    forTag:number_text];
                if([_vh7pc statusRef]->atAuto) [_view setDisplayItemDisplay:YES forTag:automono];
                break;
            case MD:
                [_view setDisplayText:@"MD" forTag:input_text];
                [_view setDisplayText:@"" forTag:number_text];
                break;
            case CD:
                [_view setDisplayText:
                    [NSString stringWithFormat:@"%@%d/%d",@"CD: ",
                        [_vh7pc statusRef]->cdTracknum,
                        [_vh7pc statusRef]->cdMaxTrack]
                    forTag:input_text];
                [_view setDisplayText:
                    [NSString stringWithFormat:@"%@:%@",
                        [self decimal2Str:[_vh7pc statusRef]->cdMin],
                        [self decimal2Str:[_vh7pc statusRef]->cdSec]]
                    forTag:number_text];
                if([_vh7pc statusRef]->repInfo==REPRAND){
                    [_view setDisplayItemDisplay:YES forTag:random_item];
                    [_view setDisplayItemDisplay:YES forTag:repeatall];
                }else if([_vh7pc statusRef]->repInfo==RAND) [_view setDisplayItemDisplay:YES forTag:random_item];
                else if([_vh7pc statusRef]->repInfo==REP) [_view setDisplayItemDisplay:YES forTag:repeat];
                else if([_vh7pc statusRef]->repInfo==RAll) [_view setDisplayItemDisplay:YES forTag:repeatall];
                break;
            case TAPE:
                [_view setDisplayText:@"TAPE/AUX" forTag:input_text];
                [_view setDisplayText:@"" forTag:number_text];
                break;
        }
    }
    if([_vh7pc statusRef]->tone==NB1) [_view setDisplayItemDisplay:YES forTag:nb1];
    else if([_vh7pc statusRef]->tone==NB2) [_view setDisplayItemDisplay:YES forTag:nb2];
    else if([_vh7pc statusRef]->tone==TONE) [_view setDisplayItemDisplay:YES forTag:tone];
    [_view setDisplayText:[NSString stringWithFormat:@"%d",[_vh7pc statusRef]->volume] forTag:volume_text];
    [_volumeSlider setIntValue:[_vh7pc statusRef]->volume];
    if([_vh7pc statusRef]->mute) [_view setDisplayItemDisplay:YES forTag:mute];
    [_view setNeedsDisplay:YES];
}


-(IBAction)performSlider:(id)sender{
    [_vh7pc changeVol:[sender intValue]];
    [self displayStatus];
}

-(IBAction)performButton:(id)sender{
    [_vh7pc getStatus];
    VH7PC_inputmode mode=[_vh7pc statusRef]->inputMode;
    switch([sender tag]){
        case band_b:
            [_vh7pc sendCommand:BAND];
            break;
        case tapeaux_b:
            [_directCtrl changeInput:[DummyClass dummyWithTag:tapeM]];
            break;
        case md_b:
            [_directCtrl changeInput:[DummyClass dummyWithTag:mdM]];
            break;
        case tuner_b:
            [_vh7pc sendCommand:SEL_TUNER];
            break;
        case cd_b:
            [_directCtrl changeInput:[DummyClass dummyWithTag:cdM]];
            break;
        case pcusb_b:
            [_directCtrl changeInput:[DummyClass dummyWithTag:usbM]];
            break;
        case repeat_b:
            if(mode==CD) [_vh7pc sendCommand:CD_REPEAT];
            else if(mode==MD) [_vh7pc sendCommand:MD_REPEAT];
            break;
        case mute_b:
            [_vh7pc sendCommand:MUTE];
            break;
        case nb_b:
            [_vh7pc sendCommand:N_B];
            break;
        case auto_b:
            [_vh7pc sendCommand:AUTO_MONO];
            break;
        case eject_b:
            if(mode==CD) [_vh7pc sendCommand:CD_EJECT];
            else if(mode==MD) [_vh7pc sendCommand:MD_EJECT];
            break;
        case skdn_b:
            if(mode==CD) [_vh7pc sendCommand:CD_SK_DN];
            else if(mode==MD) [_vh7pc sendCommand:MD_SK_DN];
            break;
        case fb_b:
            if(mode==CD) [_vh7pc sendCommand:CD_SEARCH];
            else if(mode==MD) [_vh7pc sendCommand:MD_SEARCH];
            else if(mode==FM||mode==AM) [_vh7pc sendCommand:P_CL_DN];
            break;
        case play_b:
            if(mode==CD) [_directCtrl cd:[DummyClass dummyWithTag:playcdM]];
            else if(mode==MD) [_directCtrl md:[DummyClass dummyWithTag:playmdM]];
            else if(mode==TAPE) [_directCtrl md:[DummyClass dummyWithTag:playtpM]];
            break;
        case stop_b:
            if(mode==CD) [_directCtrl cd:[DummyClass dummyWithTag:stopcdM]];
            else if(mode==MD) [_directCtrl md:[DummyClass dummyWithTag:stopmdM]];
            else if(mode==TAPE) [_directCtrl md:[DummyClass dummyWithTag:stoptpM]];
            break;
        case ff_b:
            if(mode==CD) [_vh7pc sendCommand:CD_SEARCH];
            else if(mode==MD) [_vh7pc sendCommand:MD_SEARCH];
            else if(mode==FM||mode==AM) [_vh7pc sendCommand:P_CL_UP];
            break;
        case skup_b:
            if(mode==CD) [_vh7pc sendCommand:CD_SK_UP];
            else if(mode==MD) [_vh7pc sendCommand:MD_SK_UP];
            break;
        case power_b:
            [_directCtrl power:[DummyClass dummyWithTag:0]];
            break;
        case random_b:
            if(mode==CD) [_directCtrl cd:[DummyClass dummyWithTag:randcdM]];
            else if(mode==MD) [_directCtrl md:[DummyClass dummyWithTag:randmdM]];
            break;
        case volumePlus1_b:
            [_vh7pc changeVol:[_vh7pc statusRef]->volume+1];
            [self displayStatus];
            break;
        case volumeMinus1_b:
            [_vh7pc changeVol:[_vh7pc statusRef]->volume-1];
            [self displayStatus];
            break;
    }
    [self displayStatus];
}

-(IBAction)performButtonDn:(id)sender{
    [_vh7pc getStatus];
    VH7PC_inputmode mode=[_vh7pc statusRef]->inputMode;
    if([sender tag]==ff_b){
        if(mode==CD) [_vh7pc sendCommand:CD_FF];
        else if(mode==MD) [_vh7pc sendCommand:MD_FF];
    }else if(fb_b){
        if(mode==CD) [_vh7pc sendCommand:CD_FB];
        else if(mode==MD) [_vh7pc sendCommand:MD_FB];
    }
}

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

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


- (IBAction) setControllerAlpha:(id) sender {
	[[_view window] setAlphaValue:[sender doubleValue]];
}

@end
