// Copyright (c) 2002, Peter Bentley
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// 
//   Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 
//   Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 
//   The name Peter Bentley may not be used to endorse or promote
// products derived from this software without specific prior
// written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#import "AppController.h"
#import "OmdWindow.h"
#import "OmdController.h"
#import "OmdTransport.h"
#import "OmdTocCtlr.h"
#import "slog.h"


// XXX These should be preferences
#define FAST_TICK_DELAY		0.25
#define SLOW_TICK_DELAY		3.5

#define STATUS_CLEAR_DELAY	12.0

CVSID( "$Id: AppController.m,v 1.12 2002/11/24 18:38:11 pete Exp $" );

static AppController *theAppController = nil;

void appctlr_log_out( int level, const char *msg )
{
    if( theAppController )
    {
        [theAppController logOutput: msg atLevel: level];
    }
}



@implementation AppController

- (id) init
{
    if( (self = [super init]) != nil )
    {
        delay = -1.0;
        theAppController = self;
        slog_add_handler( LOG_INFO, appctlr_log_out );
        statusClearDelay = 0.0;
    }
    return self;
}


- (void) awakeFromNib
{


    slog( LOG_INFO, "AppController - Awake from NIB called" );

    // Set up timer
    timer = [NSTimer scheduledTimerWithTimeInterval: FAST_TICK_DELAY
                                             target: self
                                           selector: @selector( fastTick: )
                                           userInfo: nil
                                            repeats: YES];
    [timer retain];
    [timer fire];		// Make timer fire once initially
}



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

- (void) fastTick: (NSTimer *) theTimer
{
    int		i;
    OmdWindow	*winctrler;
    omd_unit_t	*unit;

    for( i = 0; i < omd_num_devices(); i++ )
    {
        unit = omd_get_unit( i );
        if( unit->userdata )
        {
            winctrler = (id) unit->userdata;
            if( [winctrler pollUnit] < 0 )
            {
                slog( LOG_INFO, "Unit poll failed... rescanning bus" );
                [self scanUSB];
            }
        }
    }


    if(delay < 0.0 || delay > SLOW_TICK_DELAY )
    {
        delay = 0.0;
        [self slowTick: theTimer];
    }
    delay += FAST_TICK_DELAY;
    
    statusClearDelay += FAST_TICK_DELAY;
    if( statusClearDelay >= STATUS_CLEAR_DELAY )
    {
        statusClearDelay = 0.0;
        [[self currentWindow] status: @""];
    }
}

- (void) slowTick: (NSTimer *) theTimer
{
    slog( LOG_TRACE, "TICK!" );
    [self scanUSB];
}



- (void) scanUSB
{
    int		i;
    omd_unit_t	*unit;
    OmdWindow	*winctrler;
    
    numWindows = omd_scan_usb();
    if( numWindows < 0 )
    {
	slog( LOG_WARNING, "USB scan error" );
	return;
    }
    if( numWindows == 0 )
    {
	slog( LOG_INFO, "No devices" );
	return;
    }
    
    /* Scan USB data */
    for( i = 0; i < numWindows; i++ )
    {
	unit = omd_get_unit( i );
        if( unit->changed )
        {
            slog( LOG_INFO, "NetMD unit %d changed", i );
            winctrler = (OmdWindow *) unit->userdata;
            if( winctrler )
            {
                if( unit->present )
                {
                    slog( LOG_WARNING, "Exisitng window changed??" );
                }
                else
                {
                    slog( LOG_INFO, "Detach: Unit %d", i );
                    [winctrler close];
                    unit->userdata = NULL;
                }
            }
            else if( unit->present )
            {
                slog( LOG_INFO, "New NetMD unit detected... Creating window" );
                winctrler = [[OmdWindow alloc] initWithUnit: unit];
                [[winctrler window] makeKeyAndOrderFront: nil];
                unit->userdata = winctrler;
            }
        }
    }
}

- (void) logOutput: (const char *) message atLevel: (int) level
{
    NSString *str;

    if( level >= LOG_INFO )
    {
        str = [[NSString alloc] initWithCString: message];
        [str autorelease];
        
        [[self currentWindow] status: str];
        statusClearDelay = 0.0;
    }
}



- (OmdWindow *) currentWindow
{
    omd_unit_t	*unit;

    if( numWindows < 1 )
    {
        return nil;
    }
    // XXX This is Ÿber-bogus when we have more than 1 window
    unit = omd_get_unit( 0 );
    return (OmdWindow *) unit->userdata;
}

- (OmdController *) currentController
{
    return [[self currentWindow] getController];
}


- (OmdTransport *) currentTransport
{
    return [[self currentController] getTransport];
}

- (OmdTocCtlr *) currentTocCtlr
{
    return [[self currentController] getTocCtlr];
}


- (IBAction) play: (id) sender
{
    [[self currentTransport] play: sender];
}

- (IBAction) stop: (id) sender
{
    [[self currentTransport] stop: sender];
}

- (IBAction) pause: (id) sender
{
    [[self currentTransport] pause: sender];
}

- (IBAction) fforward: (id) sender
{
    [[self currentTransport] fforward: sender];
}

- (IBAction) rewind: (id) sender
{
    [[self currentTransport] rewind: sender];
}

- (IBAction) nextTrack: (id) sender
{
    [[self currentTransport] nextTrack: sender];
}

- (IBAction) previousTrack: (id) sender
{
    [[self currentTransport] previousTrack: sender];
}

- (IBAction) test: (id) sender
{
    slog( LOG_INFO, "Ouch! Please don't do that..." );
    [[self currentTocCtlr] test: sender];
}

- (IBAction) createGroup: (id) sender
{
    [[self currentTocCtlr] createGroup: sender];
}

- (IBAction) deleteThings: (id) sender
{
    [[self currentTocCtlr] deleteThings: sender];
}

- (BOOL) validateMenuItem: (id <NSMenuItem>) menuItem
{
    slog( LOG_TRACE, "Appcontroller validateMenuItem" );
    return [[self currentTocCtlr] validateMenuItem: menuItem];
}


@end
