//
// BusHotelSearchBoxViewController.m
// Project
//
// Created by Ziv on 16/2/17.
//
//

#import "BusHotelSearchBoxViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ImageUtils.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 "CustomDualSubtitleCell.h"
#import "CustomDualLeftRightCell.h"
#import "RoomBasedCountViewController.h"
#import "ProductSearchListVC.h"
#import "Vars.h"
#import "RangeCalendarViewController.h"

@implementation BusHotelSearchBoxParam

- (instancetype)init {
	self = [super init];
	if (self) {
		self.filter_date = [[DateFormatUtils ISO_DATE_FORMAT] format:[NSDate date]];
		self.return_date = [[DateFormatUtils ISO_DATE_FORMAT] format:[DateUtils addDays:[NSDate date] amount:1]];

		RoomBasedCountData *roomData = [[RoomBasedCountData alloc] initWithRoomNo:1];
		roomData.adultCount = 2;
		roomData.childCount = 0;
		self.roomDatas = @[roomData];
	}
	return self;
}

@end

@interface BusHotelSearchBoxViewController ()
@property (nonatomic, strong) BusHotelSearchBoxParam *busHotelSearchParam;
@property (nonatomic, strong) NSArray *cellDataArray;
@property (nonatomic, strong, readonly) NSString *roomText;
@end

@implementation BusHotelSearchBoxViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

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

// NSDictionary *busPairs = [Vars appDelegate].coreData.busDepartureArrivalPairs;
// NSDictionary *hotelDestinations = [Vars appDelegate].coreData.hotelSearchDataSource[@"destinations"];
// NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
// for (NSString *from in busPairs.allKeys) {
// NSMutableArray *toArray = [NSMutableArray array];
// for (NSString *to in busPairs[from]) {
// if ([hotelDestinations allKeysForObject:to].count > 0) {
// [toArray addObject:to];
// }
// }
// [dictionary setObject:[NSArray arrayWithArray:toArray] forKey:from];
// }
// NSDictionary *dataSource = [NSDictionary dictionaryWithDictionary:dictionary];

	self.busHotelSearchParam = [[BusHotelSearchBoxParam alloc] init];

	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CustomDualSubtitleCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([CustomDualSubtitleCell class])];
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CustomDualLeftRightCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([ CustomDualLeftRightCell class])];
	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:@"Find Bus + Hotel" forState:UIControlStateNormal];
		[button addTarget:self action:@selector(submitForm) 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:@"Bus + Hotel"];
}

#pragma mark - Segue

- (void)performSegueForDepartureCityOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	NSArray *departures = [Vars appDelegate].coreData.busDepartureArrivalPairs.allKeys;
	ComboBoxViewController *viewController = [[ComboBoxViewController alloc] init];
	viewController.title = @"Departure City";
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.suggestionTitle = @"Popular";
	viewController.historyTitle = IMLocalizedString(@"Recent Search");
	[viewController setItemsWithArray:departures];
	[viewController suggestValues:[Vars appDelegate].coreData.busSearchDataSource[@"hot_departures"]];
	[viewController setHistoryValues:[CocoaUtils objectFromUserDefaultsForKey:UserDefaultsKeyHistoryBusSearchDepartureList]];
	[viewController setDidSelectItemBlock:^(ComboBoxItem *item) {
		[self.navigationController popViewControllerAnimated:YES];
		self.busHotelSearchParam.bus_from = item.value;
		if ([[Vars appDelegate].coreData.busDepartureArrivalPairs[self.busHotelSearchParam.bus_from] count] == 1) {
			self.busHotelSearchParam.bus_to = [[Vars appDelegate].coreData.busDepartureArrivalPairs[self.busHotelSearchParam.bus_from] firstObject];
		} else {
			self.busHotelSearchParam.bus_to = nil;
		}
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	[viewController setHistoryChangedBlock:^(NSArray < ComboBoxItem * > *items) {
		[CocoaUtils synchronizeUserDefaultsBySettingWithObject:[items valueForKeyPath:@"value"] forKey:UserDefaultsKeyHistoryBusSearchDepartureList];
	}];
	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:[NSDictionary dictionaryWithObjects:departures forKeys:departures] objectForPlacemark:placemark];
	}];
	if (![StringUtils isEmpty:self.busHotelSearchParam.bus_from]) {
		[viewController selectValue:self.busHotelSearchParam.bus_from];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForArrivalCityOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	if ([StringUtils isEmpty:self.busHotelSearchParam.bus_from]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:@"Please select %@ first", @"Departure City".lowercaseString]];
		return;
	}
	ComboBoxViewController *viewController = [[ComboBoxViewController alloc] init];
	viewController.title = @"Arrival City";
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	[viewController setItemsWithArray:[Vars appDelegate].coreData.busDepartureArrivalPairs[self.busHotelSearchParam.bus_from]];
	[viewController setDidSelectItemBlock:^(ComboBoxItem *item) {
		[self.navigationController popViewControllerAnimated:YES];
		self.busHotelSearchParam.bus_to = item.value;
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	if (![StringUtils isEmpty:self.busHotelSearchParam.bus_to]) {
		[viewController selectValue:self.busHotelSearchParam.bus_to];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForRoomOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	RoomBasedCountViewController *roomViewController = [[RoomBasedCountViewController alloc] initWithRoomBasedCountDatas:self.busHotelSearchParam.roomDatas];
	roomViewController.childEnabled = YES;
	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.busHotelSearchParam.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 = @"Departure & Return";
	viewController.minimumDate = [NSDate date];
	viewController.maximumDate = [DateUtils addMonths:[DateUtils addDays:[NSDate date] amount:-1] amount:6];
	viewController.isRoundTrip = YES;
	viewController.isBusHotel = YES;
	viewController.isHeaderViewUserInteractionEnabled = NO;
	viewController.hidesBottomBarWhenPushed = YES;
	[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.busHotelSearchParam.filter_date = [[DateFormatUtils ISO_DATE_FORMAT] format:startDate];
		self.busHotelSearchParam.return_date = [[DateFormatUtils ISO_DATE_FORMAT] format:endDate];
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	if (![StringUtils isEmpty:self.busHotelSearchParam.filter_date] && ![StringUtils isEmpty:self.busHotelSearchParam.return_date]) {
		[viewController selectRangeFromStartDate:[[DateFormatUtils ISO_DATE_FORMAT] parse:self.busHotelSearchParam.filter_date] toEndDate:[[DateFormatUtils ISO_DATE_FORMAT] parse:self.busHotelSearchParam.return_date]];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Action

- (void)submitForm {
	NSString *message = nil;
	if ([StringUtils isEmpty:self.busHotelSearchParam.bus_from] || [StringUtils isEmpty:self.busHotelSearchParam.bus_to]) {
		message = @"Departure and arrival locations must be specified";
	}
	if ([StringUtils isEmpty:self.busHotelSearchParam.filter_date] || [StringUtils isEmpty:self.busHotelSearchParam.return_date]) {
		message = @"Departure and return dates must be specified";
	}
	NSDictionary *dict = [Vars appDelegate].coreData.hotelSearchDataSource[@"destinations"];
	if ([dict allKeysForObject:self.busHotelSearchParam.bus_to].count == 0) {
		message = @"Sorry, we cannot find any packages matching your search. Please change your search and try again.";
	}
	if (!message) {
		[Vars appDelegate].shopCarts.roomBasedCountDatas = self.busHotelSearchParam.roomDatas;
		[Vars appDelegate].shopCarts.adultNum = [[[Vars appDelegate].shopCarts.roomBasedCountDatas valueForKeyPath:@"@sum.adultCount"] intValue];
		[Vars appDelegate].shopCarts.childNum = [[[Vars appDelegate].shopCarts.roomBasedCountDatas valueForKeyPath:@"@sum.childCount"] intValue];
		NSArray *unshiftArray = [CocoaUtils unshiftObject:self.busHotelSearchParam.bus_from toArray:[CocoaUtils mutableArray:[CocoaUtils objectFromUserDefaultsForKey:UserDefaultsKeyHistoryBusSearchDepartureList]] count:10];
		[CocoaUtils synchronizeUserDefaultsBySettingWithObject:unshiftArray forKey:UserDefaultsKeyHistoryBusSearchDepartureList];
		ProductSearchListVC *viewController = [[ProductSearchListVC alloc] init];
		viewController.roundtrip = YES;
		viewController.isBusHotelPackage = YES;
		viewController.currentDepartString = self.busHotelSearchParam.filter_date;
		viewController.currentReturnString = self.busHotelSearchParam.return_date;
		viewController.returnCity = self.busHotelSearchParam.bus_to;
		viewController.departCity = self.busHotelSearchParam.bus_from;
		[self.navigationController pushViewController:viewController animated:YES];
	} else {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:message];
	}
}

- (void)changeToFrom {
	if ([StringUtils isEmpty:self.busHotelSearchParam.bus_from] || [StringUtils isEmpty:self.busHotelSearchParam.bus_to]) {
		return;
	}
	NSArray *tmpArray = [Vars appDelegate].coreData.busDepartureArrivalPairs[self.busHotelSearchParam.bus_to];
	BOOL isExist = [tmpArray containsObject:self.busHotelSearchParam.bus_from];
	NSString *tmpString = self.busHotelSearchParam.bus_from;
	self.busHotelSearchParam.bus_from = self.busHotelSearchParam.bus_to;
	if (isExist) {
		self.busHotelSearchParam.bus_to = tmpString;
	} else {
		self.busHotelSearchParam.bus_to = nil;
	}
	[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Property

- (NSString *)roomText {
	NSInteger peopleCount = [[self.busHotelSearchParam.roomDatas valueForKeyPath:@"@sum.peopleCount"] intValue];
	NSMutableString *string = [NSMutableString string];
	[string appendFormat:self.busHotelSearchParam.roomDatas.count > 1 ? @"%d rooms" : @"%d room", self.busHotelSearchParam.roomDatas.count];
	[string im_appendString:@", "];
	[string appendFormat:peopleCount > 1 ? @"%d guests" : @"%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.reuseIdentifier = NSStringFromClass([CustomDualSubtitleCell class]);
		[data setNeedLayoutFittingHeight];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([CustomDualLeftRightCell class]);
		[data setNeedLayoutFittingHeight];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome bedIconWithSize:20] fillColor:[UIColor lightGrayColor]];
		[data setTextBlock:^NSString *{
			@strongify(self)
			return self.roomText;
		}];
		data.textColor = [Vars defaultTintColor];
		data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForRoomOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

#pragma mark - Table view data source

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

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

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomDualSubtitleCell class])]) {
		return [UIToolkit instantiateRowHeightForTableViewCellWithNibName:NSStringFromClass([CustomDualSubtitleCell class])];
	}
	return [UIConstants defaultTableViewRowHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	@weakify(self)
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomDualSubtitleCell class])]) {
		CustomDualSubtitleCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomDualSubtitleCell class])];
		cell.imageView.userInteractionEnabled = NO;
		[CocoaUtils removeGestureRecognizerKindOfClass:[UITapGestureRecognizer class] fromView:cell.imageView];
		[cell.topSelectionButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
		[cell.bottomSelectionButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
		cell.imageView.userInteractionEnabled = YES;
		[cell.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeToFrom)]];
		cell.imageView.image = [ImageUtils rotateImage:[DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome exchangeIconWithSize:24] fillColor:[Vars defaultTintColor]] byDegrees:-90];
		cell.topTitleLabel.text = @"Leaving from";
		cell.topTitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		cell.topSubtitleLabel.text = ![StringUtils isEmpty:self.busHotelSearchParam.bus_from] ? self.busHotelSearchParam.bus_from : @"Departure City";
		cell.topSubtitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		cell.topSubtitleLabel.textColor = ![StringUtils isEmpty:self.busHotelSearchParam.bus_from] ? [Vars defaultTintColor] : [UIColor lightGrayColor];
		cell.bottomTitleLabel.text = @"Going to";
		cell.bottomTitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		cell.bottomSubtitleLabel.text = ![StringUtils isEmpty:self.busHotelSearchParam.bus_to] ? self.busHotelSearchParam.bus_to : @"Arrival City";
		cell.bottomSubtitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		cell.bottomSubtitleLabel.textColor = ![StringUtils isEmpty:self.busHotelSearchParam.bus_to] ? [Vars defaultTintColor] : [UIColor lightGrayColor];
		[cell.topSelectionButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self performSegueForDepartureCityOnTableView: tableView atIndexPath:indexPath];
		} forControlEvents:UIControlEventTouchUpInside];
		[cell.bottomSelectionButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self performSegueForArrivalCityOnTableView: tableView atIndexPath:indexPath];
		} forControlEvents:UIControlEventTouchUpInside];
		cell.topRightView = [DrawUtils tableViewCellAccessoryDisclosureIndicatorRightWithColor:[Vars defaultTintColor]];
		cell.bottomRightView = [DrawUtils tableViewCellAccessoryDisclosureIndicatorRightWithColor:[Vars defaultTintColor]];
		return cell;
	}else 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(@"Departure Date");
		cell.leftTitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		cell.leftSubtitleLabel.text = [Utility localizedStringWithStandardDateString:self.busHotelSearchParam.filter_date];
		cell.leftSubtitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		cell.leftSubtitleLabel.textColor = [Vars defaultTintColor];
		cell.rightTitleLabel.text = @"Return Date";
		cell.rightTitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		cell.rightSubtitleLabel.text = [Utility localizedStringWithStandardDateString:self.busHotelSearchParam.return_date];
		cell.rightSubtitleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		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
- (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
