//
// AppDelegate.m
// TakeTours
//
// Created by iphone development on 8/14/14.
//
//

#import "AppDelegate.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "CacheData.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "UserNotificationsManager.h"
#import "UIConstants.h"
#import "UserApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <Crashlytics/Crashlytics.h>
#import <Fabric/Fabric.h>
#import <libextobjc/EXTScope.h>
#import <PayPal-iOS-SDK/PayPalMobile.h>
#import <PiwikTracker/PiwikTracker.h>
#import <REMenu/REMenu.h>
#import <UPPaymentControl/UPPaymentControl.h>
#import <WechatOpenSDK/WXApi.h>
#ifdef POD_OF_Firebase
#import <Firebase/Firebase.h>
#endif
#ifdef POD_OF_FBSDKCoreKit
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#endif
#ifdef POD_OF_FBSDKLoginKit
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#endif
#ifdef POD_OF_GoogleSignIn
#import <GoogleSignIn/GoogleSignIn.h>
#endif
#import "Utility.h"
#import "AppDelegate+UserNotifications.h"
#import "AppNotification.h"
#import "AppTracker.h"
#import "TourUnit.h"
#import "CustomNavigationController.h"
#import "HoldingViewController.h"
#import "TabBarViewController.h"
#import "LoginViewController.h"
#import "BeanUtils.h"
#import "Vars.h"


@interface AppDelegate () <UIApplicationDelegate, WXApiDelegate>
@end

@implementation AppDelegate

#pragma mark - Application delegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	UIApplication.sharedApplication.applicationIconBadgeNumber = 0;
    self.remoteNotificationUserInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
	[WXApi registerApp:[Vars wechatAppId]];
#ifdef POD_OF_FBSDKCoreKit
	[[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
#endif
#if defined POD_OF_Firebase && defined POD_OF_GoogleSignIn
	[FIRApp configure];
	[GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID;
#endif
	[PayPalMobile initializeWithClientIdsForEnvironments:@{ PayPalEnvironmentProduction : [Vars paypalLiveClientId], PayPalEnvironmentSandbox : [Vars paypalSandboxClientId] }];
	[AppTracker sharedInstanceWithSiteID:[Vars piwikSiteId] baseURL:[NSURL URLWithString:[Vars piwikBaseUrl]]];
	[Fabric with:@[[Crashlytics class]]];
	[Utility configureRaterFlow];
	[self initPrivate];
	[self customizeAppearance];
	[self resetPreferredLanguage];
	[self resetUserDefaults];
	[self launchOrSimulate];
	return YES;
}


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
	return [self internallyApplication:app openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
	application.applicationIconBadgeNumber = 0;
	[FBSDKAppEvents activateApp];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

#pragma mark - Property

- (void)setLoginUser:(Vendor *)loginUser {
	_loginUser = loginUser;
	self.shopCarts.bookGoods.accessToken = loginUser.cookie_string;
}

#pragma mark - Public

- (void)firstLoadLogin {
	LoginViewController *viewController = [[LoginViewController alloc] init];
	viewController.firstLaunchV = YES;
	CustomNavigationController *nav = [[CustomNavigationController alloc]initWithRootViewController:viewController];
	self.window.rootViewController = nav;
}

- (void)dashboard {
	if (![self.window.rootViewController isKindOfClass:[TabBarViewController class]]) {
		self.window.rootViewController = [[TabBarViewController alloc] init];
		[AppNotification handleNotification:self.remoteNotificationUserInfo];
	}
}

- (void)logout {
	[CocoaUtils showConfirmWithTitle:IMLocalizedString(@"Log out") message:IMLocalizedString(@"Logout will not delete your bookings, the history will still be there when you login next time.") dismissalHandler:^{
		[PayPalMobile clearAllUserData];
#ifdef POD_OF_FBSDKLoginKit
		FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
		[loginManager logOut];
#endif
#ifdef POD_OF_GoogleSignIn
		[[GIDSignIn sharedInstance] signOut];
#endif
		Logout *logout = [[Logout alloc] init];
		logout.userAppId = self.loginUser.user_app_id ;
		
		NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:logout];
		[Utility performRESTRequestWithMethod:@"POST" url:logout.address parameters:requestDict success:nil];
		
		NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
		[userDefaults removeObjectForKey:UserDefaultsKeyUserID];	 
		self.loginUser = nil;
		NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
		[notificationCenter postNotificationName:SegueDidPerformNotification object:TabBarItemHome];
		[notificationCenter postNotificationName:LoginStatusDidChangeNotification object:nil];
		[self dashboard];
	}];
}

- (void)applyDefaultConfigurationForViewController:(UIViewController *)viewController {
	viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:NULL];
	if (!viewController.title && !viewController.navigationItem.titleView) {
		NSLog(@"Logo-Style2");
		viewController.navigationItem.titleView = [[UIImageView alloc] initWithImage:IMLocalizedImage(@"Logo-Style2")];
	}
}


- (void)getSearchDataSource:(NSString *)name {
	if ([name isEqualToString:@"Tour"] && !self.coreData.tourSearchDataSource) {
		GetSearchDataSource *getSearchDataSource = [[GetSearchDataSource alloc] init];
		getSearchDataSource.typeName = name;
		getSearchDataSource.apiVersion = 1;
		
		NSDictionary *requestDict = [Utility perlParamXml:[getSearchDataSource innerXML] action:getSearchDataSource.name];
		// NSLog(@"%@", requestDict);
		[Utility getJSONFromRequestWithMethod:@"GET" url:getSearchDataSource.address parameters:requestDict success:^(id jsonObject) {
			self.coreData.tourSearchDataSource = jsonObject;
		}];
	} else if ([name isEqualToString:@"Hotel"] && !self.coreData.hotelSearchDataSource) {
		GetSearchDataSource *getSearchDataSource = [[GetSearchDataSource alloc] init];
		getSearchDataSource.typeName = name;

		NSDictionary *requestDict = [Utility perlParamXml:[getSearchDataSource innerXML] action:getSearchDataSource.name];
		// NSLog(@"%@", requestDict);
		[Utility getJSONFromRequestWithMethod:@"GET" url:getSearchDataSource.address parameters:requestDict success:^(id jsonObject) {
			self.coreData.hotelSearchDataSource = jsonObject;
		}];
	}
}

#pragma mark - Private
- (void)callPhone {
	if ([Vars phone]) {
		if ([Vars tollFreePhone]) {
			NSMutableString *tollFreePhoneString = [NSMutableString string];
			[tollFreePhoneString im_appendString:[Vars tollFreePhone]];
			[tollFreePhoneString im_appendString:IMLocalizedString(WORD_DIVIDER_SPACE)];
			[tollFreePhoneString im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_LEFT)];
			[tollFreePhoneString im_appendString:IMLocalizedString(@"Toll Free")];
			[tollFreePhoneString im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_RIGHT)];
			NSArray *phoneValues = @[[Vars phone], [Vars tollFreePhone]];
			NSArray *phoneTexts = @[[Vars phone], tollFreePhoneString];
			[CocoaUtils showMessageBoxWithTitle:IMLocalizedString(@"Call") message:nil cancelActionTitle:IMLocalizedString(@"Cancel") otherActionTitles:phoneTexts actionHandler:^(NSInteger buttonIndex) {
				if (buttonIndex != -1) {
					[CocoaUtils callPhoneNumber:phoneValues[buttonIndex]];
				}
			}];
		} else {
			[CocoaUtils callPhoneNumber:[Vars phone]];
		}
	}
}

- (void)changeLanguage {
	UIAlertController *alertController = [UIAlertController alertControllerWithTitle:IMLocalizedString(@"Would you like to change the language?") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
	NSArray *languageIdentifiers = [Vars is_cn_website] ? @[@"zh-Hans", @"en"] : @[@"en", @"zh-Hans"];
	NSLocale *locale = [NSLocale currentLocale];
	for (NSString *languageIdentifier in languageIdentifiers) {
		if ([languageIdentifier isEqualToString:[IMLocalization sharedInstance].language]) {
				UIAlertAction *	destructAction = [UIAlertAction actionWithTitle:[locale displayNameForKey:NSLocaleIdentifier value:languageIdentifier] style:UIAlertActionStyleDestructive handler:nil];
				[alertController addAction:destructAction];
		} else {
				UIAlertAction *normalAction = [UIAlertAction actionWithTitle:[locale displayNameForKey:NSLocaleIdentifier value:languageIdentifier] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
					[IMLocalization sharedInstance].language = languageIdentifier;
			[[Vars appDelegate].shopCarts empty];
			[self launch];
	}];
				[alertController addAction:normalAction];
			}
		}
	UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:IMLocalizedString(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
	[alertController addAction:cancleAction];
	[self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}

- (void)initPrivate {
	self.coreData = [[MyCoreData alloc] init];
	self.shopCarts = [[ShopCarts alloc] init];
}

- (void)customizeAppearance {
	[UIWindow appearance].tintColor = [Vars defaultTintColor];

	[UITableView appearance].rowHeight = [UIConstants defaultTableViewRowHeight];
	[UITableView appearance].estimatedRowHeight = [UIConstants defaultTableViewRowHeight];
	[UITableView appearance].estimatedSectionHeaderHeight = 0;
	[UITableView appearance].estimatedSectionFooterHeight = 0;
	[UITableView appearance].tableFooterView = [[UIView alloc] init];

	[UISwitch appearance].onTintColor = [Vars defaultTintColor];
}

- (void)resetPreferredLanguage {
	if (![IMLocalization sharedInstance].hasPreferredLanguage) {
		NSString *preferredLocalization = [NSBundle mainBundle].preferredLocalizations.firstObject;
		if ([preferredLocalization isEqualToString:@"zh_CN"]) {
			preferredLocalization = @"zh-Hans";
		}
		[IMLocalization sharedInstance].language = preferredLocalization;
	}
}

- (void)resetUserDefaults {
}

- (void)launchOrSimulate {
#if DEBUG
	if (YES) {
		UIViewController *viewController = [TourUnit simulatedViewController];
		if (viewController) {
			self.window.rootViewController = viewController;
			return;
		}
	}
#endif
	[self launch];
}

- (void)launch {
	self.window.rootViewController = [[HoldingViewController alloc] init];
}

- (BOOL)internallyApplication:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
	if ([url.scheme isEqualToString:[Vars wechatAppId]]) {
		return [WXApi handleOpenURL:url delegate:self];
	} else if ([url.scheme isEqualToString:[Vars alipayUrlScheme]]) {
		if ([url.host isEqualToString:@"safepay"]) {
			[[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
				NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
				[notificationCenter postNotificationName:AlipayOrderPaymentResultNotification object:resultDic];
			}];
		}
		return YES;
	} else if ([url.scheme isEqualToString:[Vars unionpayUrlScheme]]) {
		[[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
			NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
			[notificationCenter postNotificationName:UPPaymentResultNotification object:@{ @"code" : code, @"data" : data }];
		}];
		return YES;
	}
	return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}

#pragma mark - <WXApiDelegate>

- (void)onResp:(BaseResp *)resp {
	if ([resp isKindOfClass:[PayResp class]]) {
		NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
		[notificationCenter postNotificationName:WXPayRespNotification object:resp];
	}
}

@end
