//
//  TagDemoAppDelegate.m
//  TagDemo
//
//  Created by jcassidy on 10-11-15.
//  Copyright 2010 Visible Assets Inc. All rights reserved.
//

#import "TagDemoAppDelegate.h"
#import "RootViewController.h"


@implementation TagDemoAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize baseStation;
@synthesize version;


#pragma mark -
#pragma mark Application lifecycle

// ***************************************************************
// *                                                             
// * application: didFinishLaunchingWithOptions:  
// *
// * - set software version number
// * - initialize basestation and establish communications
// * - setup default preferences 
// *                                                             
// ***************************************************************

- (BOOL) application:(UIApplication *) application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions 
{    
	NSUserDefaults *defaults;
	
	// set app version number
	version = 0.1;
    
	[self setupDefaults];
	
  	// create and initialize the basestation - note: connect method will complain if connect fails
	baseStation = [[BaseStation alloc] init];
	[baseStation setType:BLADE_TYPE];
	[self connect];
	
	[[baseStation communicationsLink] clear];
	
	// Add the tab bar controller's current view as a subview of the window
	[window addSubview:navigationController.view];
	[window makeKeyAndVisible];
	
	defaults = [NSUserDefaults standardUserDefaults];
	beepFilename = [defaults  stringForKey:@"beep_sound"];
	
	return YES;
}

// ***************************************************************
// *                                                             
// * setupDefaults = copy default values from settings bundle to user defaults if required                          
// *                                                             
// ***************************************************************

- (void) setupDefaults 
{
	NSString		*settingsPath, *plistPath, *key;
	NSDictionary	*settingsDictionary;
	NSArray		*preferencesArray;
	NSUserDefaults	*defaults;
	id				value, defaultValue;
	
	// get the plist location from the settings bundle
	settingsPath	= [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Settings.bundle"];
	plistPath		= [settingsPath stringByAppendingPathComponent:@"Root.plist"];
	
	// get the preference specifiers array which contains the settings
	settingsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
	preferencesArray	 = [settingsDictionary objectForKey:@"PreferenceSpecifiers"];
	
	// use the shared defaults object
	defaults = [NSUserDefaults standardUserDefaults];
	
	// for each preference item, set its default if there is no value set
	for( NSDictionary *item in preferencesArray ) {		
		// get the item key, if there is no key then we can skip it
		key = [item objectForKey:@"Key"];
		if( key ) {			
			// check to see if the value and default value are set
			// if a default value exists and the value is not set, use the default
			value = [defaults objectForKey:key];
			defaultValue = [item objectForKey:@"DefaultValue"];
			if( defaultValue && !value ) {
				[defaults setObject:defaultValue forKey:key];
			}
		}
	}
	
	// write the changes to disk
	[defaults synchronize];
}

// ***************************************************************
// *                                                             
// * connect = conntect to transceiver board peripherals                          
// *                                                             
// ***************************************************************

- (void) connect
{
	BOOL			status;
	UIAlertView		*alert;
	NSUserDefaults	*defaults;
	
	// open connection to basestation and check for success
	status = [baseStation open:@"internal"];
	if( status == YES ) {
		// extract version from controller and keep it in the application delegate for use elsewhere
		[[baseStation communicationsLink] firmwareVersion];
		
		// ping the transceiver to make certain it is available
		if( ![baseStation ping] ) {
			alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Transceiver not responding" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
			[alert show];
			[alert release];
		}			
	}
	else{
		// can't communicate with authentication controller!
		alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Authentication Controller not responding" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
		[alert show];
		[alert release];
	}
	
	// initialize accessories (bar code, ethernet, etc...) based on preferences
	defaults = [NSUserDefaults standardUserDefaults];
	if( [defaults boolForKey:@"bar_code_scanner"] )
		[[baseStation communicationsLink] scannerInit];
}	


- (void)applicationWillResignActive:(UIApplication *)application 
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application 
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application 
{
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application 
{
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


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


@end

