//
//  BundlePrefereableClockAppDelegate.m
//  BundlePrefereableClock
//
//  Created by Chris Adamson on 6/23/08.
//  Copyright Subsequently and Furthermore, Inc. 2008. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//


#import "BundlePrefereableClockViewController.h"

@implementation BundlePrefereableClockViewController

@synthesize timeLabel, timeZoneLabel;

//START:code.BundlePreferableClock.keysanddefault
NSString *TwentyFourHourPrefKey = @"24HourDisplay";
NSString *TimeZonePrefKey = @"TimeZone";
NSString *DefaultTimeZonePref = @"America/Detroit";
//END:code.BundlePreferableClock.keysanddefault


/* Attempt to load the prefs from bundle, assign defaults if absent
 */
//START:code.BundlePreferableClock.loadprefs
- (void) loadPrefs {
	// set app defaults
	timeZoneName = DefaultTimeZonePref;
	// read user prefs
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *userTimeZone = [defaults stringForKey:TimeZonePrefKey];
	if (userTimeZone != NULL)
		timeZoneName = userTimeZone;
	[userTimeZone release];
	show24Hour = [defaults boolForKey:TwentyFourHourPrefKey];
}
//END:code.BundlePreferableClock.loadprefs


// see formats at http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns

//START:code.BundlePreferableClock.restofthegui
-(void) setClockFormatter {
	if (clockFormatter == nil) {
		clockFormatter = [[NSDateFormatter alloc] init];
	}
	if (show24Hour)
		[clockFormatter setDateFormat: @"H:mm:ss"];
	else
		[clockFormatter setDateFormat: @"h:mm:ss a"];
	// also update time zone
	[clockFormatter setTimeZone: [NSTimeZone timeZoneWithName: timeZoneName]];
}

-(void) updateClockView {
	NSDate *dateNow = [NSDate date];
	timeLabel.text = [clockFormatter stringFromDate: dateNow];
	timeZoneLabel.text = timeZoneName;
}

-(void) startClock {
	[self updateClockView];
	if (!clockViewUpdateTimer) {
		clockViewUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
				target:self
				selector:@selector (updateClockView)
				userInfo:NULL
				repeats:YES];
	}
}

- (void)viewDidLoad {
	[super viewDidLoad];
	[self loadPrefs];
	[self setClockFormatter];
	[self startClock];
}
//END:code.BundlePreferableClock.restofthegui


/*
 Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
	[super loadView];
}
 */

/*
 Implement viewDidLoad if you need to do additional setup after loading the view.
 */


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


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


@end
