//
// HotelSearchBoxViewController.m
// Project
//
// Created by Ziv on 15/12/8.
//
//

#import "HotelSearchBoxViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "LocationManager.h"
#import "CalendarViewController.h"
#import "ComboBoxViewController.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/A2DynamicDelegate.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "AppTracker.h"
#import "HotelSearchListViewController.h"
#import "CustomDualLeftRightCell.h"
#import "RoomBasedCountViewController.h"
#import "RangeCalendarViewController.h"
#import "Vars.h"

static NSInteger const ktableviewCellHeight = 60;

@interface HotelSearchBoxViewController ()

@property (nonatomic, strong) NSArray *cellDataArray;

@property (nonatomic, strong) NSArray *roomDatas;
@property (nonatomic, strong) NSString *destination;
@property (nonatomic, strong) NSString *checkInDate;
@property (nonatomic, strong) NSString *checkOutDate;
@property (nonatomic, strong) NSString *keyWords;

@property (nonatomic, strong, readonly) NSString *destinationText;
@property (nonatomic, strong, readonly) NSString *roomText;

@end

@implementation HotelSearchBoxViewController

- (instancetype)init {
	if (self = [super init]) {
		self.title = IMLocalizedString(@"Find Hotels");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

//	[[Vars appDelegate].shopCarts empty];

	[[AppTracker sharedInstance] sendView:[self class]];
	
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CustomDualLeftRightCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([CustomDualLeftRightCell class])];
	
	self.checkInDate = [[DateFormatUtils ISO_DATE_FORMAT] format:[NSDate date]];
	self.checkOutDate = [[DateFormatUtils ISO_DATE_FORMAT] format:[DateUtils addDays:[NSDate date] amount:2]];

	if (!self.roomDatas) {
		RoomBasedCountData *roomData = [[RoomBasedCountData alloc] initWithRoomNo:1];
		roomData.adultCount = 2;
		roomData.childCount = 0;
		self.roomDatas = @[roomData];
	}

	if (YES) {
		UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight] + 15 * 2)];
		UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
		button.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]);
		button.backgroundColor = [Vars defaultTintColor];
		button.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
		[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[button setTitle:IMLocalizedString(@"Find Hotels") forState:UIControlStateNormal];
		[button addTarget:self action:@selector(findHotels) forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:button];
		[footerView addSubview:button];
		self.tableView.tableFooterView = footerView;
	}
	[self buildCellDataSource];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	[[Vars appDelegate] getSearchDataSource:@"Hotel"];
}

#pragma mark - Segue

- (void)performSegueForDestinationOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	NSDictionary *destinations = [Vars appDelegate].coreData.hotelSearchDataSource[@"destinations"];
	ComboBoxViewController *viewController = [[ComboBoxViewController alloc] init];
	viewController.title = IMLocalizedString(@"Destination");
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.historyTitle = IMLocalizedString(@"Recent Search");
	[viewController setItemsWithDictionary:destinations];
	[viewController setHistoryValues:[CocoaUtils objectFromUserDefaultsForKey:UserDefaultsKeyHistoryHotelSearchDestinationList]];
	[viewController setDidSelectItemBlock:^(ComboBoxItem *item) {
		[self.navigationController popViewControllerAnimated:YES];
		self.destination = item.value;
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	[viewController setHistoryChangedBlock:^(NSArray < ComboBoxItem * > *items) {
		[CocoaUtils synchronizeUserDefaultsBySettingWithObject:[items valueForKeyPath:@"value"] forKey:UserDefaultsKeyHistoryHotelSearchDestinationList];
	}];
	viewController.allowsLocation = YES;
	[viewController setGeocodeBlock:^(ComboBoxViewController *viewController) {
		[Utility requestLocationWithCompletion:^(BOOL granted, CLLocation *location, NSError *error) {
			if (!granted || !location) {
				[viewController updatePlacemark:nil];
			} else {
				[Utility reverseGeocodeLocation:location completionHandler:^(CLPlacemark *placemark, NSError *error) {
					[viewController updatePlacemark:placemark];
				}];
			}
		}];
	}];
	[viewController setPlacemarkFormattingBlock:^NSString *(CLPlacemark *placemark) {
		return placemark.locality;
	}];
	[viewController setPlacemarkTransformationBlock:^id (CLPlacemark *placemark) {
		return [Destination localityTransformation:destinations objectForPlacemark:placemark];
	}];
	if (![StringUtils isEmpty:self.destination]) {
		[viewController selectValue:self.destination];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForRoomOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	RoomBasedCountViewController *roomViewController = [[RoomBasedCountViewController alloc] initWithRoomBasedCountDatas:self.roomDatas];
	roomViewController.childEnabled = YES;
	// roomViewController.minimumPeopleCount = 1;
	// roomViewController.maximumPeopleCount = 7;
	roomViewController.minimumAdultCount = 1;
	roomViewController.maximumAdultCount = 4;
	roomViewController.maximumChildCount = 3;
	roomViewController.minimumChildAge = 1;
	roomViewController.maximumChildAge = 17;
	roomViewController.preferredChildAge = 12;
	[roomViewController setDidCancelBlock:^{
		[self.navigationController popViewControllerAnimated:YES];
	}];
	[roomViewController setDidDoneBlock:^(NSArray *countDatas) {
		[self.navigationController popViewControllerAnimated:YES];
		self.roomDatas = countDatas;
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	[self.navigationController pushViewController:roomViewController animated:YES];
}

- (void)performSegueForDateRangeOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	RangeCalendarViewController *viewController = [[RangeCalendarViewController alloc] init];
	viewController.title =IMLocalizedString(@"Select Dates");
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.isRoundTrip = YES;
	viewController.isHotel = YES;
	viewController.isHeaderViewUserInteractionEnabled = NO;
	viewController.minimumDate = [NSDate date];
	viewController.maximumDate = [DateUtils addYears:[NSDate date] amount:1];
	viewController.hidesBottomBarWhenPushed = YES;
	[viewController selectRangeFromStartDate:self.checkInDate toEndDate:self.checkOutDate];
	[viewController setDidCancelBlock:^{
		[self.navigationController popViewControllerAnimated:YES];
	}];
	[viewController setDidDoneRangeBlock:^(NSDate *startDate, NSDate *endDate) {
			if (!startDate || !endDate) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select departure date and return date"];
				return;
			}
		[self.navigationController popViewControllerAnimated:YES];
		self.checkInDate = [[DateFormatUtils ISO_DATE_FORMAT] format:startDate];
		self.checkOutDate = [[DateFormatUtils ISO_DATE_FORMAT] format:endDate];
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	if (![StringUtils isEmpty:self.checkInDate] && ![StringUtils isEmpty:self.checkOutDate]) {
		[viewController selectRangeFromStartDate:[[DateFormatUtils ISO_DATE_FORMAT] parse:self.checkInDate] toEndDate:[[DateFormatUtils ISO_DATE_FORMAT] parse:self.checkOutDate]];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Action

- (void)findHotels {
	if (![self checkInputParame]) {
		return;
	}
	NSArray *unshiftArray = [CocoaUtils unshiftObject:self.destination toArray:[CocoaUtils mutableArray:[CocoaUtils objectFromUserDefaultsForKey:UserDefaultsKeyHistoryHotelSearchDestinationList]] count:10];
	[CocoaUtils synchronizeUserDefaultsBySettingWithObject:unshiftArray forKey:UserDefaultsKeyHistoryBusSearchDepartureList];
	HotelSearchListViewController *viewController = [[HotelSearchListViewController alloc] init];
	HotelSearchPaginationParam *hotelParam = [[HotelSearchPaginationParam alloc] init];
	hotelParam.destination = self.destination;
	hotelParam.checkIn = self.checkInDate;
	hotelParam.checkOut = self.checkOutDate;
	hotelParam.roomInfo = self.roomDatas;
	hotelParam.keywords = self.keyWords;
	viewController.hotelSearchParam = hotelParam;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Property

- (NSString *)destinationText {
	return [Vars appDelegate].coreData.hotelSearchDataSource[@"destinations"][self.destination];
}

- (NSString *)roomText {
	NSInteger peopleCount = [[self.roomDatas valueForKeyPath:@"@sum.peopleCount"] intValue];
	NSMutableString *string = [NSMutableString string];
	[string appendFormat:self.roomDatas.count > 1 ? IMLocalizedString(@"%d rooms") : IMLocalizedString(@"%d room"), self.roomDatas.count];
	[string im_appendString:IMLocalizedString(PUNCTUATION_COMMA)];
	[string im_appendString:IMLocalizedString(WORD_DIVIDER_SPACE)];
	[string appendFormat:peopleCount > 1 ? IMLocalizedString(@"%d guests") : IMLocalizedString(@"%d guest"), peopleCount];
	return [NSString stringWithString:string];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseHeight = [UIConstants defaultTableViewRowHeight] + 5 * 2;
		data.style = UITableViewCellStyleSubtitle;
		data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:28] fillColor:[UIColor lightGrayColor]];
		data.accessoryType = UITableViewCellAccessoryNone;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		data.text = IMLocalizedString(@"Destination");
		[data setDetailTextBlock:^NSString *{
			@strongify(self)
			return [StringUtils isEmpty:self.destinationText] ? IMLocalizedString(@"Anywhere") : self.destinationText;
		}];
		data.textFont = [UIFont systemFontOfSize:14];
		data.detailTextFont = [UIFont systemFontOfSize:15];
		[data setDetailTextColorBlock:^UIColor *{
			@strongify(self)
			return [StringUtils isEmpty:self.destinationText] ? [UIColor lightGrayColor] : [Vars defaultTintColor];
		}];
		[data setRequiredValidationRuleBlock:^BOOL {
			@strongify(self)
			return self.destination;
		}];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForDestinationOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.accessoryType = UITableViewCellAccessoryNone;
		data.reuseIdentifier = NSStringFromClass([CustomDualLeftRightCell class]);
		[data setNeedLayoutFittingHeight];
		[array addObject:data];
	}

	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome bedIconWithSize:24] fillColor:[UIColor lightGrayColor]];
		[data setTextBlock:^NSString *{
			@strongify(self)
			return self.roomText;
		}];
		data.textColor = [Vars defaultTintColor];
		data.textFont = [UIFont systemFontOfSize:15];
		data.accessoryType = UITableViewCellAccessoryNone;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForRoomOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.accessoryType = UITableViewCellAccessoryNone;
		data.style = UITableViewCellStyleSubtitle;
		data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome searchIconWithSize:24] fillColor:[UIColor lightGrayColor]];
		data.editingType = TableViewCellEditingTypeTextField;
		data.placeholder = IMLocalizedString(@"Optional keywords");
		data.observedObject = self;
		data.keyPath = @"keyWords";
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

- (BOOL)checkInputParame {
	[self.tableView endEditing:YES];
	for (int row = 0; row < self.cellDataArray.count; row++) {
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
		TableViewCellData *data = self.cellDataArray[row];
		if (![data validateRequired]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[data requiredValidationMessage:NO] dismissalHandler:^{
				[UIToolkit tableView:self.tableView atIndexPath:indexPath didFocusWithData:data];
			}];
			return NO;
		}
		if (![data validateIntegrity]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[data integrityValidationMessage:NO] dismissalHandler:^{
				[UIToolkit tableView:self.tableView atIndexPath:indexPath didFocusWithData:data];
			}];
			return NO;
		}
	}
	return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.cellDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	@weakify(self)
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomDualLeftRightCell class])]) {
		CustomDualLeftRightCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomDualLeftRightCell class])];
		[cell.leftSelectionButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
		[cell.rightSelectionButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
		cell.imageView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome calendarIconWithSize:24] fillColor:[UIColor lightGrayColor]];
		cell.leftTitleLabel.text = IMLocalizedString(@"Check-in date");
		cell.leftTitleLabel.font = [UIFont systemFontOfSize:14];
		cell.leftSubtitleLabel.text = [Utility localizedStringWithStandardDateString:self.checkInDate];
		cell.leftSubtitleLabel.font = [UIFont systemFontOfSize:15];
		cell.leftSubtitleLabel.textColor = [Vars defaultTintColor];
		cell.rightTitleLabel.text =  IMLocalizedString(@"Check-out date");
		cell.rightTitleLabel.font = [UIFont systemFontOfSize:14];
		cell.rightSubtitleLabel.text = [Utility localizedStringWithStandardDateString:self.checkOutDate];
		cell.rightSubtitleLabel.font = [UIFont systemFontOfSize:15];
		cell.rightSubtitleLabel.textColor = [Vars defaultTintColor];
		[cell.leftSelectionButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self performSegueForDateRangeOnTableView: tableView atIndexPath:indexPath];
		} forControlEvents:UIControlEventTouchUpInside];
		[cell.rightSelectionButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self performSegueForDateRangeOnTableView: tableView atIndexPath:indexPath];
		} forControlEvents:UIControlEventTouchUpInside];
		return cell;
	}
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return ktableviewCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

@end
