//
// HoldingViewController.m
// IvyMedia
//
// Created by paul on 8/28/14.
//
//

#import "HoldingViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "AnswersManager.h"
#import "CocoaUtils.h"
#import "NetUtils.h"
#import "Utility.h"
#import "UIToolkit.h"
#import "PerlWS.h"
#import "InitAppResponseJsonMapper.h"
#import "Vars.h"
#import "AnswersManager.h"


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

@implementation HoldingViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view from its nib.
	self.imageView.image = IMLocalizedImage(@"Logo-Style1");
}

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

#pragma mark - Private

- (void)checkVersionPic {
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	InitApp *initApp = [[InitApp alloc] init];
	BOOL allowsHijack = NO;
	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]];
	
	__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 = initApp.login_info.auto_login ? [userDefaults integerForKey:UserDefaultsKeyUserID] : 0;
	}
	__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;
			}
			[Vars appDelegate].coreData.slide_images = response.app_info_response.slide_images;
			[Vars appDelegate].coreData.hot_destination_images = response.app_info_response.hot_destination_images;
			[userDefaults removeObjectForKey:@"SearchSourceDigest"];
			[userDefaults removeObjectForKey:@"SearchSourceDigestV1"];
			[userDefaults removeObjectForKey:@"tourSearchDataSourceDigest"];
			[userDefaults removeObjectForKey:@"hotelSearchDataSourceDigest"];
			if (![StringUtils isEmpty:response.app_info_response.tour_search_data_source_digest]) {
				NSString *key = [NSString stringWithFormat:@"%@ %@", UserDefaultsPrefixTourSearchDataSourceDigest, [IMLocalization sharedInstance].language];
				if (![response.app_info_response.tour_search_data_source_digest isEqualToString:[userDefaults stringForKey:key]]) {
					[Vars appDelegate].coreData.tourSearchDataSource = nil;
				}
				[userDefaults setObject:response.app_info_response.tour_search_data_source_digest forKey:key];
			}
			if (![StringUtils isEmpty:response.app_info_response.hotel_search_data_source_digest]) {
				NSString *key = [NSString stringWithFormat:@"%@ %@", UserDefaultsPrefixHotelSearchDataSourceDigest, [IMLocalization sharedInstance].language];
				if (![response.app_info_response.hotel_search_data_source_digest isEqualToString:[userDefaults stringForKey:key]]) {
					[Vars appDelegate].coreData.hotelSearchDataSource = nil;
				}
				[userDefaults setObject:response.app_info_response.hotel_search_data_source_digest forKey:key];
			}
			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
