//
//  DatePickerDataProvider.m
//
//

#import "DatePickerDataProvider.h"

@implementation DatePickerDataProvider {
	NSDictionary * _contents;
	BOOL _didLoad;
	NSDateFormatter * _dateFormatter;
}

- (BOOL)didLoad {
	return _didLoad;
}

- (void)setControl:(UIDatePicker *)control {
	_control = control;
	_didLoad = YES;
}

- (void)valueDidChange:(UIDatePicker *)control {
	control.unixTime = control.date.timeIntervalSince1970;
	[self updateContents];
	[self notifyObservers];
}

- (void)updateContents {
	
    if (!_dateFormatter) {
		_dateFormatter = [[NSDateFormatter alloc] init];
	}
	
	if (_control.datePickerMode == UIDatePickerModeTime) {
		[_dateFormatter setDateStyle:NSDateFormatterNoStyle];
		[_dateFormatter setTimeStyle:NSDateFormatterShortStyle];
	}
	else if (_control.datePickerMode == UIDatePickerModeDate) {
		[_dateFormatter setDateStyle:NSDateFormatterMediumStyle];
		[_dateFormatter setTimeStyle:NSDateFormatterNoStyle];
	}
	else if (_control.datePickerMode == UIDatePickerModeDateAndTime) {
		[_dateFormatter setDateStyle:NSDateFormatterMediumStyle];
		[_dateFormatter setTimeStyle:NSDateFormatterShortStyle];
	}
	NSString * formattedDate = [_dateFormatter stringFromDate:[_control date]];
	
	_contents = @{
				  @"countDownDuration": [NSNumber numberWithInteger:_control.countDownDuration],
				  @"unixTime": [NSNumber numberWithLongLong:_control.unixTime],
				  @"formattedDate": formattedDate,
				  };

}

- (id)contents {
	return _contents;
}

@end

// Use a special storace, since the 'date' property is not reliable.
static NSMutableDictionary * unixTimeStorage;
static int UIDatePickerTagCtr = 1;

@implementation UIDatePicker (DataProvider)

- (void)setDataProvider:(DatePickerDataProvider *)provider {
	provider.control = self;
	[provider updateContents];
	[self addTarget:provider action:@selector(valueDidChange:) forControlEvents:UIControlEventValueChanged];
}

- (void)prepareForSpecialStorage {
	if (!self.tag) self.tag = UIDatePickerTagCtr++;
	if (!unixTimeStorage) unixTimeStorage = @{}.mutableCopy;
}

- (long long)unixTime {
	[self prepareForSpecialStorage];
	long long time = [unixTimeStorage[[NSNumber numberWithInteger:self.tag]] longLongValue];
	//NSLog(@"get unixTime: %lld", time);
	return time;
}

- (void)setUnixTime:(long long)time {
	//NSLog(@"setUnixTime: %lld", time);
	[self prepareForSpecialStorage];
	unixTimeStorage[[NSNumber numberWithInteger:self.tag]] = [NSNumber numberWithLongLong:time];
	dispatch_async(dispatch_get_main_queue(), ^{
		self.date = [NSDate dateWithTimeIntervalSince1970:(double)time];
	});
}

@end
