//
// TimeRecordViewController.m
// GotoBus
//
// Created by vae on 2018/3/15.
//

#import "TimeClock.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "UIToolkit.h"
#import <AFNetworking/AFHTTPSessionManager.h>
#import <Valet/Valet.h>
#import "Utility.h"
#import "PerlWS.h"
#import "Vars.h"

@interface TimeClock ()
@property (nonatomic, assign) BOOL isClockingIn;
@property (nonatomic, strong, readonly) NSString *deviceIdentifier;
@property (nonatomic, strong) NSArray *ipUrlArray;
@property(nonatomic, strong) dispatch_semaphore_t signal;
@property(nonatomic, assign) BOOL isGetIpAddress;
@end

@implementation TimeClock


#pragma mark - Public

+ (TimeClock *)sharedInstance {
	static dispatch_once_t once;
	static TimeClock *instance;
	dispatch_once(&once, ^{
		instance = [[self alloc] init];
	});
	return instance;
}

- (void)reload {
	if (![Vars appDelegate].loginUser.is_support || ![Vars appDelegate].loginUser.enable_time_clock_punch) {
		return;
	}
	
	[self performRequestForGetSupportTimeClockStatus];
}

- (void)sendAction {
	if (![Vars appDelegate].loginUser.is_support || ![Vars appDelegate].loginUser.enable_time_clock_punch) {
		return;
	}
	if ([Vars appDelegate].loginUser.device_registered) {
		if (self.isClockingIn) {
			[CocoaUtils showConfirmWithTitle:IMLocalizedString(@"Information") message:@"Please remember to checkout, before you leave." dismissalHandler:^{
				[self performRequestForGetIpAddress];
			}];
		} else {
			[CocoaUtils showConfirmWithTitle:IMLocalizedString(@"Information") message:@"Please check in to record your working hours."  dismissalHandler:^{
				[self performRequestForGetIpAddress];
			}];
		}
	} else {
		[CocoaUtils showConfirmWithTitle:IMLocalizedString(@"Information") message:@"Please register your device." dismissalHandler:^{
			[self performRequestForRegisterSupportDevice];
		}];
	}
}

- (NSString *)currentTitle {
	if (![Vars appDelegate].loginUser.is_support || ![Vars appDelegate].loginUser.enable_time_clock_punch) {
		return nil;
	}
	if ([Vars appDelegate].loginUser.device_registered) {
		if (self.isClockingIn) {
			return @"CheckOut";
		} else {
			return @"Check In";
		}
	} else {
		return @"Register Device";
	}
}

- (UIColor *)currentTitleColor {
	if (![Vars appDelegate].loginUser.is_support || ![Vars appDelegate].loginUser.enable_time_clock_punch) {
		return [UIColor lightGrayColor];
	}
	if ([Vars appDelegate].loginUser.device_registered) {
		if (self.isClockingIn) {
			return [Vars defaultTintColor];
		}
	}
	return [UIColor lightGrayColor];
}

#pragma mark - Network

- (void)performRequestForGetSupportTimeClockStatus {
	GetSupportTimeClockStatus *getSupportTimeClockStatus = [[GetSupportTimeClockStatus alloc] init];

	NSDictionary *requestDict = [Utility perlParamXml:[getSupportTimeClockStatus innerXML] action:getSupportTimeClockStatus.name];

	[Utility getXMLFromRequestWithMethod:@"GET" url:getSupportTimeClockStatus.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@",responseStr);
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[GetSupportTimeClockStatusResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetSupportTimeClockStatusResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				self.isClockingIn = response.check_flag;
			}
            [[TimeClock sharedInstance] sendAction];

		}
	}];
}

-(void)performRequestForGetIpAddress{
	self.signal = dispatch_semaphore_create(0);
	UIViewController *this = [CocoaUtils topMostViewController];
	[CocoaUtils showBusyIndicator:this.view];
	[self performRequestForSouhuIp];
	dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, 120 * NSEC_PER_SEC);
	dispatch_semaphore_wait(self.signal, timeout);
	if (!self.isGetIpAddress) {
		[self performRequestForTaoBaoIp];
	}
}

-(void)performRequestForSouhuIp{
	NSString *requestUrl = @"https://pv.sohu.com/cityjson?ie=utf-8";
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestUrl]];
	NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
	NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
	NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
		if (error) {
			dispatch_semaphore_signal(self.signal);
			return ;
		}
	   	NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
		if ([StringUtils isEmpty:responseString]) {
			dispatch_semaphore_signal(self.signal);
			return;
		}
		NSRange startRange = [responseString rangeOfString:@"{"];
		NSRange endRange = [responseString rangeOfString:@"}"];
		if (startRange.location == NSNotFound || endRange.location == NSNotFound) {
			dispatch_semaphore_signal(self.signal);
			return;
		}
		NSRange range = NSMakeRange(startRange.location, endRange.location - startRange.location + endRange.length);
		NSString *ipJsonString = [responseString substringWithRange:range];
		NSData *jsonData = [ipJsonString dataUsingEncoding:NSUTF8StringEncoding];
		NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
		NSString *ipString = ipDic[@"cip"];
		if (![StringUtils isEmpty:ipString]) {
			dispatch_async(dispatch_get_main_queue(), ^{
				[self performRequestForPunchSupportTimeClock:ipString];
			});
			self.isGetIpAddress = YES;
		}
		dispatch_semaphore_signal(self.signal);
	}];
	[task resume];
}

-(void)performRequestForTaoBaoIp{
	
	NSString *requestUrl = @"https://www.taobao.com/help/getip.php";
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestUrl]];
	NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
	NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
	NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
		if (error) {
			dispatch_semaphore_signal(self.signal);
			return ;
		}
		NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
		NSArray *stringArray = [responseString componentsSeparatedByString:@"\""];
		NSString *ipString = [NSString string];
		if (stringArray.count > 2) {
			ipString = stringArray[1];
		}
		if (![StringUtils isEmpty:ipString]) {
			dispatch_async(dispatch_get_main_queue(), ^{
				[self performRequestForPunchSupportTimeClock:ipString];
			});
		}
		dispatch_semaphore_signal(self.signal);
	}];
	[task resume];
}

- (void)performRequestForPunchSupportTimeClock:(NSString *)ipStr{

	PunchSupportTimeClock *punchSupportTimeClock = [[PunchSupportTimeClock alloc] init];
	punchSupportTimeClock.deviceIdentifier = [Utility deviceIdentifier];
	punchSupportTimeClock.officeIp = ipStr;

	NSDictionary *requestDict = [Utility perlParamXml:[punchSupportTimeClock innerXML] action:punchSupportTimeClock.name];
	
	[Utility getXMLFromRequestWithMethod:@"GET" url:punchSupportTimeClock.address parameters:requestDict beforeSend:nil success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@",responseStr);
		UIViewController *this = [CocoaUtils topMostViewController];
		[CocoaUtils hideBusyIndicator:this.view];
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[PunchSupportTimeClockResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			PunchSupportTimeClockResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				if (response.success) {
					if (self.isClockingIn) {
						[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Checkout Success"];
						self.isClockingIn = NO;
					} else {
						[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Check In Success"];
						self.isClockingIn = YES;
					}
				} else {
					if (self.isClockingIn) {
						[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Checkout Failed"];
					} else {
						[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Check In Failed"];
					}
				}
			}
		}
	} complete:nil];
}

- (void)performRequestForRegisterSupportDevice {
	RegisterSupportDevice *registerSupportDevice = [[RegisterSupportDevice alloc] init];
	registerSupportDevice.deviceIdentifier = [Utility deviceIdentifier];

	NSDictionary *requestDict = [Utility perlParamXml:[registerSupportDevice innerXML] action:registerSupportDevice.name];

	[Utility getXMLFromRequestWithMethod:@"GET" url:registerSupportDevice.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[RegisterSupportDeviceResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			RegisterSupportDeviceResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				if (response.success) {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Register Device Success"];
					[Vars appDelegate].loginUser.device_registered = YES;
					self.isClockingIn = NO;
				} else {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Register Device Failed"];
				}
			}
		}
	}];
}

@end
