//
//  MainViewController.m
//  FlippingPrefereableClock
//
//  Created by Chris Adamson on 6/14/09.
//  Copyright Subsequently and Furthermore, Inc. 2009. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//


#import "MainViewController.h"
#import "MainView.h"


@implementation MainViewController

@synthesize timeLabel, timeZoneLabel, clockPrefs;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}

//START:code.FlippingPreferableClock.setclocktotimezonename
-(void) setClockToTimeZoneName: (NSString*) tz uses24Hour: (BOOL) u24h {
	[timeZoneName release];
	[tz retain];
	timeZoneName = tz;
	// set time formatter with 24 hour preference and time zone
	if (clockFormatter == nil) {
		clockFormatter = [[NSDateFormatter alloc] init];
	}
	// see formats at
	// http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns
	[clockFormatter setTimeZone: [NSTimeZone timeZoneWithName: tz]];
	if (u24h)
		[clockFormatter setDateFormat: @"HH:mm:ss"];
	else
		[clockFormatter setDateFormat: @"h:mm:ss a"];
}
//END:code.FlippingPreferableClock.setclocktotimezonename


//START:code.FlippingPreferableClock.udpateclockview
-(void) updateClockView {
	if (! clockFormatter) { 
		timeLabel.text = @""; 
		timeZoneLabel.text = @""; 
		return; 
	} 
	NSDate *dateNow = [NSDate date]; 
	timeLabel.text = [clockFormatter stringFromDate: dateNow]; 
	timeZoneLabel.text = timeZoneName; 
} 
//END:code.FlippingPreferableClock.udpateclockview

//START:code.FlippingPreferableClock.setupnstimer
-(void) startClock { 
	// since timer's first callback will occur after interval, 
	// do one up-front refresh 
	[self updateClockView]; 
	// now set up timer to repeatedly call updateClockView 
	clockViewUpdateTimer = [NSTimer
		scheduledTimerWithTimeInterval:0.2 
		target:self 
		selector:@selector (updateClockView) 
		userInfo:nil 
		repeats:YES]; 
} 
//END:code.FlippingPreferableClock.setupnstimer


#pragma mark load prefs

//START:code.FlippingPreferableClock.initandloadprefs
- (void) initPrefsFilePath { 
	NSString *documentsDirectory = 
	[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 
	prefsFilePath = [documentsDirectory stringByAppendingPathComponent: 
			@"flippingprefs.plist"]; 
	[prefsFilePath retain]; 
} 

- (void) loadPrefs { 
	if (prefsFilePath == nil) 
		[self initPrefsFilePath]; 
	if ([[NSFileManager defaultManager] fileExistsAtPath: prefsFilePath]) { 
		clockPrefs = [[NSMutableDictionary alloc] 
			initWithContentsOfFile: prefsFilePath]; 
	}
	else { 
		clockPrefs = [[NSMutableDictionary alloc] initWithCapacity: 2]; 
		[clockPrefs setObject: DEFAULT_TIME_ZONE_PREF 
			forKey: TIME_ZONE_PREF_KEY]; 
		[clockPrefs setObject: DEFAULT_TWENTY_FOUR_HOUR_PREF 
			forKey: TWENTY_FOUR_HOUR_PREF_KEY]; 
	} 
	NSString *prefTimeZone = [clockPrefs objectForKey: TIME_ZONE_PREF_KEY];
	BOOL uses24Hour = [(NSString*)
		[clockPrefs objectForKey: TWENTY_FOUR_HOUR_PREF_KEY] boolValue];
	[self setClockToTimeZoneName: prefTimeZone uses24Hour: uses24Hour];
} 
//END:code.FlippingPreferableClock.initandloadprefs

//START:code.FlippingPreferableClock.saveprefs
- (void) savePrefs {
	[clockPrefs writeToFile: prefsFilePath atomically: YES]; 
}
//END:code.FlippingPreferableClock.saveprefs

#pragma mark vc lifecycle methods

/*
 */
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	[self loadPrefs];
	[self startClock];
}


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


//START:code.FlippingPreferableClock.flipsideviewcontrollerdidfinish
- (void)flipsideViewControllerDidFinish:
		(FlipsideViewController *)controller {
	timeZoneName = [controller selectedTimeZone];
	BOOL uses24Hour = [controller uses24Hour];
	NSString *selected24HourDisplayS = uses24Hour ? @"YES" : @"NO";
	[clockPrefs setObject: timeZoneName forKey: TIME_ZONE_PREF_KEY]; 
	[clockPrefs setObject: selected24HourDisplayS 
		forKey: TWENTY_FOUR_HOUR_PREF_KEY]; 
	// save prefs to documents folder 
	[self savePrefs];
	
	// update display to changed prefs
	[self setClockToTimeZoneName: timeZoneName uses24Hour: uses24Hour];
	[self updateClockView];
	
	// from template
	[self dismissModalViewControllerAnimated:YES];
}
//END:code.FlippingPreferableClock.flipsideviewcontrollerdidfinish


- (IBAction)showInfo {    
	
	FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
	controller.delegate = self;
	
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:controller animated:YES];
	
	[controller release];
}



/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


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


@end
