//
// TourSearchFilterViewController.m
// IvyMedia
//
// Created by haibara on 9/1/14.
//
//

#import "TourSearchFilterViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "CalendarViewController.h"
#import "DrawUtils.h"
#import "NavigationItemSheet.h"
#import "AutoCompleteViewController.h"
#import "DropDownViewController.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <TTRangeSlider/TTRangeSlider.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "Vars.h"

@interface TourSearchFilterViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSArray *cellDataArray;
@property (nonatomic, strong) NSMutableArray *tmpDurations;
@property (nonatomic, strong) NSArray *availableDates;
@end

@implementation TourSearchFilterViewController

- (instancetype)init {
	self = [super init];
	if (self) {
		// Custom initialization
		self.title = IMLocalizedString(@"Filter Search Results");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	self.navigationController.navigationBar.translucent = YES;
	[self buildCellDataSource];
}

#pragma mark - Property

- (NSArray *)availableDates {
	if (!_availableDates) {
		_availableDates = [self.tourFilterDict[@"filterInventory"] bk_map:^id (id obj) {
			return [[DateFormatUtils ISO_DATE_FORMAT] parse:obj];
		}];
	}
	return _availableDates;
}

#pragma mark - Private

- (void)popToSearchList {
	TourSearchListViewController *viewController = [CocoaUtils lastViewControllerWithClass:[TourSearchListViewController class] onNavigationController:self.navigationController];
	if (![viewController.tourSearchParam isEqual:self.tourSearchParam]) {
		viewController.tourSearchParam = self.tourSearchParam;
		[viewController clearTourSearchResults];
	}
	[self.navigationController popToViewController:viewController animated:YES];
}

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	NSArray *regions = self.tourFilterDict[@"regions"];
	NSArray *destinations = self.tourFilterDict[@"destinations"];
	NSArray *departures = self.tourFilterDict[@"departures"];
	NSArray *duration = self.tourFilterDict[@"duration"];
	NSArray *startDates = self.tourFilterDict[@"filterInventory"];
	NSDictionary *promotionType = self.tourFilterDict[@"promotion"];
	NSString *minPrice = self.tourFilterDict[@"minPrice"];
	NSString *maxPrice = self.tourFilterDict[@"maxPrice"];
	if (regions.count > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"regions";
		data.text = IMLocalizedString(@"Regions");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	if (destinations.count > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"destinations";
		data.text = IMLocalizedString(@"Destinations");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	if (departures.count > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"departures";
		data.text = IMLocalizedString(@"Departures");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	if (duration.count > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"duration";
		data.text = IMLocalizedString(@"Duration - days");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	if (startDates.count > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"startDates";
		data.text = IMLocalizedString(@"Start Dates");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	if (minPrice.floatValue >= 0 && maxPrice.floatValue > minPrice.floatValue) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"priceRange";
		data.text = IMLocalizedString(@"Price Range");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"keyWords";
		data.text = IMLocalizedString(@"Keywords");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	if (promotionType.count > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"promotionType";
		data.text = IMLocalizedString(@"Promotion");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

#pragma mark - Collection view methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
	return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return [self.tourFilterDict[@"duration"] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";
	UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
	UILabel *label = [cell.contentView viewWithTag:NSStringFromClass([UILabel class]).hash];
	if (!label) {
		label = [[UILabel alloc] init];
		label.tag = NSStringFromClass([UILabel class]).hash;
		[cell.contentView addSubview:label];
	}
	NSString *duration = self.tourFilterDict[@"duration"][indexPath.row];
	UICollectionViewFlowLayout *layout = collectionView.collectionViewLayout;
	label.frame = CGRectZeroMakeSize(layout.itemSize);
	label.text = duration;
	label.textAlignment = NSTextAlignmentCenter;
	label.textColor = [UIColor blackColor];
	if ([self.tmpDurations containsObject:duration]) {
		label.backgroundColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
	} else {
		label.backgroundColor = [UIColor lightGrayColor];
	}
	return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
	[collectionView deselectItemAtIndexPath:indexPath animated:YES];
	NSString *duration = self.tourFilterDict[@"duration"][indexPath.row];
	if ([self.tmpDurations containsObject:duration]) {
		[self.tmpDurations removeObject:duration];
	} else {
		[self.tmpDurations addObject:duration];
	}
	[collectionView reloadItemsAtIndexPaths:@[indexPath]];
}

#pragma mark - Table view methods

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

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

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	if ([data.identifier isEqualToString:@"regions"]) {
		DropDownViewController *viewController = [[DropDownViewController alloc] init];
		viewController.title = data.text;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
		for (NSDictionary *region in self.tourFilterDict[@"regions"]) {
			NSString *name = region[@"name"];
			NSArray *destinations = region[@"destinations"];
			NSMutableArray *values = [NSMutableArray array];
			NSMutableArray *labels = [NSMutableArray array];
			for (NSDictionary *destination in destinations) {
				NSString *id = destination[@"id"];
				NSString *name = destination[@"name"];
				NSInteger productNumber = [destination[@"productNumber"] intValue];
				NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] im_initWithString:name];
				NSMutableString *string = [NSMutableString string];
				[string im_appendString:IMLocalizedString(WORD_DIVIDER_SPACE)];
				[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_LEFT)];
				[string appendFormat:@"%d", productNumber];
				[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_RIGHT)];
				[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:string attributes:@{ NSForegroundColorAttributeName : [UIColor darkGrayColor] }]];
				[values addObject:id];
				[labels addObject:[[NSAttributedString alloc] initWithAttributedString:attributedString]];
			}
			[viewController addItemsWithValues:[NSArray arrayWithArray:values] andLabels:[NSArray arrayWithArray:labels] groupedTitle:name];
		}
		NSMutableArray *destinations = [NSMutableArray arrayWithArray:self.tourSearchParam.destinations];
		if (destinations.count > 0) {
			[viewController selectValues:destinations];
		}
		[viewController setDidDoneBlock:^(NSArray *items) {
			[destinations removeObjectsInArray:[[self.tourFilterDict[@"regions"] valueForKeyPath:@"@unionOfArrays.destinations"] valueForKeyPath:@"id"]];
			[destinations removeObjectsInArray:[[self.tourFilterDict[@"destinations"] valueForKeyPath:@"@unionOfArrays.attractions"] valueForKeyPath:@"id"]];
			[destinations addObjectsFromArray:[items valueForKeyPath:@"value"]];
			self.tourSearchParam.destinations = [destinations valueForKeyPath:@"@distinctUnionOfObjects.self"];
			[self popToSearchList];
		}];
		[viewController setDidCancelBlock:^{
			[self.navigationController popViewControllerAnimated:YES];
		}];
		[self.navigationController pushViewController:viewController animated:YES];
	} else if ([data.identifier isEqualToString:@"destinations"]) {
		DropDownViewController *viewController = [[DropDownViewController alloc] init];
		viewController.title = data.text;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
		for (NSDictionary *destination in self.tourFilterDict[@"destinations"]) {
			NSString *name = destination[@"name"];
			NSArray *attractions = destination[@"attractions"];
			NSMutableArray *values = [NSMutableArray array];
			NSMutableArray *labels = [NSMutableArray array];
			for (NSDictionary *attraction in attractions) {
				NSString *id = attraction[@"id"];
				NSString *name = attraction[@"name"];
				NSInteger productNumber = [attraction[@"productNumber"] intValue];
				NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] im_initWithString:name];
				NSMutableString *string = [NSMutableString string];
				[string im_appendString:IMLocalizedString(WORD_DIVIDER_SPACE)];
				[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_LEFT)];
				[string appendFormat:@"%d", productNumber];
				[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_RIGHT)];
				[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:string attributes:@{ NSForegroundColorAttributeName : [UIColor darkGrayColor] }]];
				[values addObject:id];
				[labels addObject:[[NSAttributedString alloc] initWithAttributedString:attributedString]];
			}
			[viewController addItemsWithValues:[NSArray arrayWithArray:values] andLabels:[NSArray arrayWithArray:labels] groupedTitle:name];
		}
		if (self.tourSearchParam.destinations.count > 0) {
			[viewController selectValues:self.tourSearchParam.destinations];
		}
		[viewController setDidDoneBlock:^(NSArray *items) {
			NSMutableArray *destinations = [NSMutableArray arrayWithArray:self.tourSearchParam.destinations];
			[destinations removeObjectsInArray:[[self.tourFilterDict[@"destinations"] valueForKeyPath:@"@unionOfArrays.attractions"] valueForKeyPath:@"id"]];
			[destinations addObjectsFromArray:[items valueForKeyPath:@"value"]];
			self.tourSearchParam.destinations = [destinations valueForKeyPath:@"@distinctUnionOfObjects.self"];
			[self popToSearchList];
		}];
		[viewController setDidCancelBlock:^{
			[self.navigationController popViewControllerAnimated:YES];
		}];
		[self.navigationController pushViewController:viewController animated:YES];
	} else if ([data.identifier isEqualToString:@"departures"]) {
		DropDownViewController *viewController = [[DropDownViewController alloc] init];
		viewController.title = data.text;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
		NSMutableArray *values = [NSMutableArray array];
		NSMutableArray *labels = [NSMutableArray array];
		for (NSDictionary *departure in self.tourFilterDict[@"departures"]) {
			NSString *id = departure[@"id"];
			NSString *name = departure[@"name"];
			NSInteger productNumber = [departure[@"productNumber"] intValue];
			NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] im_initWithString:name];
			NSMutableString *string = [NSMutableString string];
			[string im_appendString:IMLocalizedString(WORD_DIVIDER_SPACE)];
			[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_LEFT)];
			[string appendFormat:@"%d", productNumber];
			[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_RIGHT)];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:string attributes:@{ NSForegroundColorAttributeName : [UIColor darkGrayColor] }]];
			[values addObject:id];
			[labels addObject:[[NSAttributedString alloc] initWithAttributedString:attributedString]];
		}
		[viewController setItemsWithValues:[NSArray arrayWithArray:values] andLabels:[NSArray arrayWithArray:labels]];
		if (self.tourSearchParam.departures.count > 0) {
			[viewController selectValues:self.tourSearchParam.departures];
		}
		[viewController setDidDoneBlock:^(NSArray *items) {
			self.tourSearchParam.departures = [items valueForKeyPath:@"value"];
			[self popToSearchList];
		}];
		[viewController setDidCancelBlock:^{
			[self.navigationController popViewControllerAnimated:YES];
		}];
		[self.navigationController pushViewController:viewController animated:YES];
	} else if ([data.identifier isEqualToString:@"duration"]) {
		self.tmpDurations = [NSMutableArray arrayWithArray:self.tourSearchParam.duration];
		static NSString *CellIdentifier = @"Cell";
		CGFloat spacing = 10;
		CGFloat cols = 7;
		CGFloat wh = (CGRectGetWidth(self.tableView.frame) - spacing * (cols + 1)) / cols;
		UICollectionViewFlowLayout *collectionViewLayout = [[UICollectionViewFlowLayout alloc] init];
		collectionViewLayout.itemSize = CGSizeMake(wh, wh);
		collectionViewLayout.sectionInset = UIEdgeInsetsMake(spacing, spacing, spacing, spacing);
		collectionViewLayout.minimumInteritemSpacing = spacing;
		collectionViewLayout.minimumLineSpacing = spacing;
		UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:collectionViewLayout];
		collectionView.backgroundColor = [UIColor whiteColor];
		collectionView.delegate = self;
		collectionView.dataSource = self;
		[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CellIdentifier];
		[collectionView autoSetDimensionsToSize:collectionViewLayout.collectionViewContentSize];
		NavigationItemSheet *sheet = [[NavigationItemSheet alloc] initWithViews:@[collectionView] handler:^{
			self.tourSearchParam.duration = [NSArray arrayWithArray:self.tmpDurations];
			[self popToSearchList];
		}];
		[sheet show];
	} else if ([data.identifier isEqualToString:@"startDates"]) {
		CalendarViewController *viewController = [[CalendarViewController alloc] init];
		viewController.title = data.text;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
		viewController.allowsToday = NO;
		viewController.allowsMultipleSelection = YES;
		viewController.calendarManager.minimumDate = self.availableDates.firstObject;
		viewController.calendarManager.maximumDate = self.availableDates.lastObject;
		viewController.calendarManager.enabledDates = self.availableDates;
		if (self.tourSearchParam.startDates.count > 0) {
			[viewController selectDates:[self.tourSearchParam.startDates bk_map:^id (id obj) {
				return [[DateFormatUtils ISO_DATE_FORMAT] parse:obj];
			}]];
		}
		[viewController setDidCancelBlock:^{
			[self.navigationController popViewControllerAnimated:YES];
		}];
		[viewController setDidDoneMultipleBlock:^(NSArray<NSDate *> *dates) {
			self.tourSearchParam.startDates = [dates bk_map:^id (id obj) {
				return [[DateFormatUtils ISO_DATE_FORMAT] format:obj];
			}];
			[self popToSearchList];
		}];
		[self.navigationController pushViewController:viewController animated:YES];
	} else if ([data.identifier isEqualToString:@"priceRange"]) {
		NSString *minPrice = self.tourFilterDict[@"minPrice"];
		NSString *maxPrice = self.tourFilterDict[@"maxPrice"];
		NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
		formatter.numberStyle = NSNumberFormatterCurrencyStyle;
		formatter.minimumFractionDigits = 0;
		formatter.maximumFractionDigits = 2;
		formatter.currencySymbol = @"$";
		TTRangeSlider *rangeSlider = [[TTRangeSlider alloc] init];
		rangeSlider.numberFormatterOverride = formatter;
		rangeSlider.minValue = minPrice.floatValue;
		rangeSlider.maxValue = maxPrice.floatValue;
		if (![StringUtils isEmpty:self.tourSearchParam.minPrice]) {
			rangeSlider.selectedMinimum = self.tourSearchParam.minPrice.floatValue;
		} else {
			rangeSlider.selectedMinimum = rangeSlider.minValue;
		}
		if (![StringUtils isEmpty:self.tourSearchParam.maxPrice]) {
			rangeSlider.selectedMaximum = self.tourSearchParam.maxPrice.floatValue;
		} else {
			rangeSlider.selectedMaximum = rangeSlider.maxValue;
		}
		UIView *view = [[UIView alloc] init];
		[view addSubview:rangeSlider];
		[rangeSlider autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(15, 15, 5, 15)];
		NavigationItemSheet *sheet = [[NavigationItemSheet alloc] initWithViews:@[view] handler:^{
			self.tourSearchParam.minPrice = [NSString stringWithFormat:@"%g", rangeSlider.selectedMinimum];
			self.tourSearchParam.maxPrice = [NSString stringWithFormat:@"%g", rangeSlider.selectedMaximum];
			[self popToSearchList];
		}];
		[sheet show];
	} else if ([data.identifier isEqualToString:@"keyWords"]) {
		AutoCompleteViewController *viewController = [[AutoCompleteViewController alloc] init];
		viewController.title = data.text;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
		[viewController setItemsWithArray:[Vars appDelegate].coreData.tourSearchDataSource[@"keywords"]];
		if (![StringUtils isEmpty:self.tourSearchParam.keyWords]) {
			[viewController searchString:self.tourSearchParam.keyWords];
		}
		[viewController setDidSelectStringBlock:^(NSString *string) {
			self.tourSearchParam.keyWords = string;
			[self popToSearchList];
		}];
		[self.navigationController pushViewController:viewController animated:YES];
	} else if ([data.identifier isEqualToString:@"promotionType"]) {
		DropDownViewController *viewController = [[DropDownViewController alloc] init];
		viewController.title = data.text;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
		NSMutableArray *values = [NSMutableArray array];
		NSMutableArray *labels = [NSMutableArray array];
		for (NSDictionary *promotion in self.tourFilterDict[@"promotion"]) {
			for (id key in promotion.allKeys) {
				[values addObject:key];
				[labels addObject:promotion[key]];
			}
		}
		[viewController setItemsWithValues:[NSArray arrayWithArray:values] andLabels:[NSArray arrayWithArray:labels]];
		if (self.tourSearchParam.promotionType.count > 0) {
			[viewController selectValues:self.tourSearchParam.promotionType];
		}
		[viewController setDidDoneBlock:^(NSArray *items) {
			self.tourSearchParam.promotionType = [items valueForKeyPath:@"value"];
			[self popToSearchList];
		}];
		[viewController setDidCancelBlock:^{
			[self.navigationController popViewControllerAnimated:YES];
		}];
		[self.navigationController pushViewController:viewController animated:YES];
	}
}

@end
