//
// StartScreenViewController.m
// Project
//
// Created by Ziv on 15/12/4.
//
//

#import "LaunchScreenViewController.h"
#import "LoginViewController.h"
#import "CustomNavigationController.h"
#import "TabBarViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "AnswersManager.h"
#import "CocoaUtils.h"
#import "NetUtils.h"
#import "UIToolkit.h"
#import <Crashlytics/Crashlytics.h>
#import "Utility.h"
#import "JGotoWS.h"
#import "NotificationApi.h"
#import "InitAppResponseJsonMapper.h"
#import "BeanUtils.h"
#import "Vars.h"
#import "UserNotificationsManager.h"

@interface LaunchScreenViewController ()
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@end

@implementation LaunchScreenViewController

- (void)viewDidLoad {
	[super viewDidLoad];

	self.imageView.image = [UIImage imageNamed:[CocoaUtils launchImageName]];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	[self checkVersionPic];
}

- (void)checkVersionPic {
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	InitApp *initApp = [[InitApp alloc] init];
	initApp.login_info.auto_login = YES;
	initApp.device_info.device_type = 1;
	initApp.device_info.unique_identifier = [Utility deviceIdentifier];
	initApp.device_info.model_name = [UIDeviceHardware platformStringSimple];
	initApp.device_info.system_name = [NSString stringWithFormat:@"%@ %@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion]];
	
	BOOL allowsHijack = NO;
	__block	BOOL autoLoginSucceed = NO;
	__block	BOOL needUpdate = NO;

#if DEBUG
	allowsHijack = YES;
#endif
	if (allowsHijack && [Vars autoLoginUserId] > 0) {
		initApp.login_info.user_id = [Vars autoLoginUserId];
	} else {
		initApp.login_info.user_id = [userDefaults integerForKey:UserDefaultsKeyUserID];
	}
	__block BOOL isAutoLogin = initApp.login_info.user_id > 0;
	
	NSDictionary *requestDict = [Utility perlParamXml:[initApp innerXML] action:initApp.name];
	// NSLog(@"%@", requestDict);
	[NetUtils adviceSettings:@{NetworkSettingRequestTimeout : @5}];
	[Utility getXMLFromRequestWithMethod:@"GET" url:initApp.address parameters:requestDict beforeSend:nil success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		InitAppResponseJsonMapper *mapper = [[InitAppResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			InitAppResponse *response = mapper.response;
			if (response.app_info_response.update_required) {
				needUpdate = YES;
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Update your app first") dismissalHandler:^{
					[CocoaUtils loadProductWithITunesItemIdentifier:[Vars appId]];
				}];
				return;
			}
			[userDefaults removeObjectForKey:@"SearchSourceDigest"];
			[userDefaults removeObjectForKey:@"SearchSourceDigestV1"];
			if (![StringUtils isEmpty:response.app_info_response.bus_search_data_source_digest]) {
				if (![response.app_info_response.bus_search_data_source_digest isEqualToString:[userDefaults stringForKey:UserDefaultsKeyBusSearchDataSourceDigest]]) {
					[Vars appDelegate].coreData.busSearchDataSource = nil;
				}
				[userDefaults setObject:response.app_info_response.bus_search_data_source_digest forKey:UserDefaultsKeyBusSearchDataSourceDigest];
			}
			if (![StringUtils isEmpty:response.app_info_response.hotel_search_data_source_digest]) {
				if (![response.app_info_response.hotel_search_data_source_digest isEqualToString:[userDefaults stringForKey:UserDefaultsKeyHotelSearchDataSourceDigest]]) {
					[Vars appDelegate].coreData.hotelSearchDataSource = nil;
				}
				[userDefaults setObject:response.app_info_response.hotel_search_data_source_digest forKey:UserDefaultsKeyHotelSearchDataSourceDigest];
			}
			if (![StringUtils isEmpty:response.app_info_response.guest_checkout_promotion_text]) {
				[Vars appDelegate].coreData.guestCheckoutPromotionText = response.app_info_response.guest_checkout_promotion_text;
			}
			if ([StringUtils isEmpty:response.login_response.error]) {
				if ([StringUtils isEmpty:response.login_response.user.cookie_string]) {
				} else {
					[Vars appDelegate].loginUser = response.login_response.user;
					autoLoginSucceed = YES;
				}
			}
		}
	}  complete:^{
		if (needUpdate) {
			return;
		}
		
		if (isAutoLogin) {
			[AnswersManager logLoginWithMethod:@"Auto" success:autoLoginSucceed];
		}
		if ([Vars appDelegate].loginUser){
			[[Vars appDelegate] dashboard];
		} else {
			[[Vars appDelegate] firstLoadLogin];
		}
	}];
}


@end
