//
// HotelSearchFilterViewController.m
// Project
//
// Created by Ziv on 15/12/14.
//
//

#import "HotelSearchFilterViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "NavigationItemSheet.h"
#import "ImageUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import <TTRangeSlider/TTRangeSlider.h>
#import "Utility.h"
#import "HotelSearchData.h"
#import "HotelSearchListViewController.h"
#import "Vars.h"

@interface HotelSearchFilterViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) IBOutlet UITableView *leftTableView;
@property (nonatomic, weak) IBOutlet UITableView *rightTableView;
@property (nonatomic, weak) IBOutlet UIButton *confirmBtn;

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *onscreenBottomConstraint;

@property (nonatomic, strong) NSArray *leftCellDataArray;
@property (nonatomic, strong) NSArray *rightCellDataArray;

@property (nonatomic, assign) BOOL isCustomPrice;
@property (nonatomic, assign) NSInteger lastSelectedLeftRow;
@property (nonatomic, strong, readonly) NSNumber *filterMinPrice;
@property (nonatomic, strong, readonly) NSNumber *filterMaxPrice;

- (IBAction)confirm:(id)sender;

@end

@implementation HotelSearchFilterViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.lastSelectedLeftRow = NSNotFound;

	self.confirmBtn.backgroundColor = [Vars defaultTintColor];
	[self.confirmBtn setTitle:IMLocalizedString(@"Confirm") forState:UIControlStateNormal];
	[Utility addRoundedBorderToButton:self.confirmBtn];

	[self buildLeftCellDataSource];
	[self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
	[self tableView:self.leftTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
	self.rightTableView.contentInset = self.leftTableView.contentInset;
	self.rightTableView.scrollIndicatorInsets = self.leftTableView.scrollIndicatorInsets;
}

- (void)viewWillLayoutSubviews {
	[super viewWillLayoutSubviews];

	if (@available(iOS 11, *)) {
		self.onscreenBottomConstraint.constant = self.view.safeAreaInsets.bottom + 15;
	} else {
		self.onscreenBottomConstraint.constant = self.bottomLayoutGuide.length + 15;
	}
}

#pragma mark - Property

- (NSNumber *)filterMinPrice {
	return self.hotelFilterDict[@"minPrice"];
}

- (NSNumber *)filterMaxPrice {
	return self.hotelFilterDict[@"maxPrice"];
}

#pragma mark - Action

- (IBAction)confirm:(id)sender {
	HotelSearchListViewController *viewController = [CocoaUtils lastViewControllerWithClass:[HotelSearchListViewController class] onNavigationController:self.navigationController];
	if (![viewController.hotelSearchParam isEqual:self.hotelSearchParam]) {
		viewController.hotelSearchParam = self.hotelSearchParam;
		[viewController clearHotelSearchResults];
	}
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)changePriceOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	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 = self.filterMinPrice.floatValue;
	rangeSlider.maxValue = self.filterMaxPrice.floatValue;
	if (self.isCustomPrice && ![StringUtils isEmpty:self.hotelSearchParam.minPrice]) {
		rangeSlider.selectedMinimum = self.hotelSearchParam.minPrice.floatValue;
	} else {
		rangeSlider.selectedMinimum = rangeSlider.minValue;
	}
	if (self.isCustomPrice && ![StringUtils isEmpty:self.hotelSearchParam.maxPrice]) {
		rangeSlider.selectedMaximum = self.hotelSearchParam.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.isCustomPrice = YES;
		self.hotelSearchParam.minPrice = [NSString stringWithFormat:@"%g", rangeSlider.selectedMinimum];
		self.hotelSearchParam.maxPrice = [NSString stringWithFormat:@"%g", rangeSlider.selectedMaximum];
		[tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone];
	}];
	[sheet show];
}

#pragma mark - Segue

#pragma mark - Private

- (NSDictionary *)getFilterDictWithIdentifier:(NSString *)identifier  {
	id filterDict = self.hotelFilterDict[identifier];
	if (filterDict == [NSNull null]) {
		filterDict = @{};
	} else if ([filterDict isKindOfClass:[NSArray class]]) {
		filterDict = [NSDictionary dictionaryWithObjects:filterDict forKeys:filterDict];
	}
	return filterDict;
}

- (void)buildLeftCellDataSource {
	NSMutableArray *identifiers = [NSMutableArray array];
	if (!self.hotelSearchParam.isBusHotelPackage) {
		if (self.filterMinPrice.floatValue >= 0 && self.filterMaxPrice.floatValue > self.filterMinPrice.floatValue) {
			[identifiers addObject:@"priceRange"];
		}
	}
	for (NSString *identifier in @[@"stars", @"brands", @"locations", @"boards", @"amenities"]) {
		NSDictionary *filterDict = [self getFilterDictWithIdentifier:identifier];
		if (filterDict.count > 0) {
			[identifiers addObject:identifier];
		}
	}
	if (YES) {
		[identifiers addObject:@"orderBy"];
	}
	NSDictionary *titles = @{ @"priceRange" : IMLocalizedString(@"Price Range"), @"stars" : IMLocalizedString(@"Star Rating"), @"brands" : IMLocalizedString(@"Brands"), @"locations" : [Vars is_cn_website] ? IMLocalizedString(@"Places") : @"Locations", @"boards" : [Vars is_cn_website] ? IMLocalizedString(@"Meals") : @"Board Base", @"amenities" : IMLocalizedString(@"Amenities"), @"orderBy" : IMLocalizedString(@"Sort by") };
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	for (NSString *identifier in identifiers) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.backgroundColor = [UIColor groupTableViewBackgroundColor];
		data.selectedBackgroundColor = [UIColor whiteColor];
		data.text = titles[identifier];
		data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			if (self.lastSelectedLeftRow != indexPath.row) {
				self.lastSelectedLeftRow = indexPath.row;
				[self buildRightCellDataSourceWithIdentifier:identifier];
				[self.rightTableView reloadData];
			}
		}];
		[array addObject:data];
	}
	self.leftCellDataArray = [NSArray arrayWithArray:array];
}

- (void)buildRightCellDataSourceWithIdentifier:(NSString *)identifier {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	if ([identifier isEqualToString:@"priceRange"]) {
		NSMutableArray *lowPrices = [NSMutableArray array];
		NSMutableArray *heightPrices = [NSMutableArray array];
		int minPrice = ceilf(self.filterMinPrice.floatValue);
		int maxPrice = floorf(self.filterMaxPrice.floatValue);
		int maxCount = 0;
		int dX = 0;
		for (int i = 5; i > 0; i--) {
			dX = (maxPrice - minPrice + 1) / i;
			if (dX >= 2) {
				maxCount = i;
				break;
			}
		}
		for (int num = 0; num < maxCount; ++num) {
			[lowPrices addObject:@(minPrice + dX * num)];
			[heightPrices addObject:num == maxCount - 1 ? @(maxPrice) : @(minPrice + dX * (num + 1) - 1)];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"No preference");
			data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
			data.textColor = [Vars defaultTintColor];
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				@strongify(self)
				if (self.isCustomPrice) {
				} else if ([StringUtils isEmpty:self.hotelSearchParam.minPrice] && [StringUtils isEmpty:self.hotelSearchParam.maxPrice]) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				self.isCustomPrice = NO;
				self.hotelSearchParam.minPrice = nil;
				self.hotelSearchParam.maxPrice = nil;
				[tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		for (int num = 0; num < maxCount; ++num) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			CGFloat lowPrice = [lowPrices[num] floatValue];
			CGFloat heightPrice = [heightPrices[num] floatValue];
			data.text = [NSString stringWithFormat:@"$%g - $%g", lowPrice, heightPrice];
			data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				@strongify(self)
				if (self.isCustomPrice) {
				} else if (self.hotelSearchParam.minPrice.floatValue == lowPrice && self.hotelSearchParam.maxPrice.floatValue == heightPrice) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				self.isCustomPrice = NO;
				self.hotelSearchParam.minPrice = [NSString stringWithFormat:@"%g", lowPrice];
				self.hotelSearchParam.maxPrice = [NSString stringWithFormat:@"%g", heightPrice];
				[tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			[data setTextBlock:^NSString *{
				@strongify(self)
				if (self.isCustomPrice) {
					return [NSString stringWithFormat:@"$%g - $%g", self.hotelSearchParam.minPrice.floatValue, self.hotelSearchParam.maxPrice.floatValue];
				} else {
					return IMLocalizedString(@"Advanced");
				}
			}];
			data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				@strongify(self)
				if (self.isCustomPrice) {
					return UITableViewCellAccessoryCheckmark;
				} else {
					return UITableViewCellAccessoryDisclosureIndicatorDown;
				}
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.isCustomPrice) {
				} else {
					self.isCustomPrice = YES;
					self.hotelSearchParam.minPrice = nil;
					self.hotelSearchParam.maxPrice = nil;
				}
				[self changePriceOnTableView:tableView atIndexPath:indexPath];
			}];
			[array addObject:data];
		}
	} else if ([identifier isEqualToString:@"orderBy"]) {
		NSDictionary *filterSortby = @{ @"popular" : IMLocalizedString(@"Best Seller"), @"low_price" : IMLocalizedString(@"Price from low"), @"high_price" : IMLocalizedString(@"Price from high"), @"star_rating" : IMLocalizedString(@"Star Rating") };
		NSArray *filterSortbyArray = @[@"popular", @"low_price", @"high_price", @"star_rating"];
		for (NSString *key in filterSortbyArray) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = [NSString stringWithFormat:@"%@%@", [Vars is_cn_website] ? IMLocalizedString(@"By") : @"", filterSortby[key]];
			data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				@strongify(self)
				if ([self.hotelSearchParam.orderBy isEqualToString:key]) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				self.hotelSearchParam.orderBy = key;
				[tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
	} else {
		NSMutableArray *hotelParamItem = [self.hotelSearchParam valueForKey:identifier];
		if (!hotelParamItem) {
			hotelParamItem = [NSMutableArray array];
			[self.hotelSearchParam setValue:hotelParamItem forKey:identifier];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"No preference");
			data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
			data.textColor = [Vars defaultTintColor];
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				if (hotelParamItem.count == 0) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				[hotelParamItem removeAllObjects];
				[tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		NSDictionary *filterDict = [self getFilterDictWithIdentifier:identifier];
		NSArray *items = [filterDict keysSortedByValueUsingComparator:^NSComparisonResult (id obj1, id obj2) {
			if ([identifier isEqualToString:@"stars"]) {
				return [obj1 compare:obj2];
			} else {
				return [obj1 localizedCaseInsensitiveCompare:obj2];
			}
		}];
		for (NSString *key in items) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			if ([identifier isEqualToString:@"amenities"]) {
				data.image = [ImageUtils imageNamed:[HotelSearchData imageNameWithAmenityId:key.intValue] tintColor:[CocoaUtils colorWithRGBs:StandardColorBlue]];
			}
			if ([identifier isEqualToString:@"stars"]) {
				data.attributedText = [self getHotelRatingWithCount:key.intValue];
			} else {
				data.text = filterDict[key];
				data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
				data.allowsTextLineWrapping = YES;
				[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
					return [NSString stringWithFormat:@"%@ %d", identifier, [hotelParamItem containsObject:key]];
				}];
			}
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				if ([hotelParamItem containsObject:key]) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				if ([hotelParamItem containsObject:key]) {
					[hotelParamItem removeObject:key];
				} else {
					[hotelParamItem addObject:key];
				}
				[tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
	}
	self.rightCellDataArray = [NSArray arrayWithArray:array];
}

- (NSAttributedString *)getHotelRatingWithCount:(NSInteger)count {
	NSAttributedString *lightStar = [DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome starIconWithSize:24] fillColor:[CocoaUtils colorWithRGBs:0x0694d4]];
	NSAttributedString *darkStar = [DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome starIconWithSize:24] fillColor:[UIColor lightGrayColor]];
	NSMutableAttributedString *attributedStar = [[NSMutableAttributedString alloc] init];
	for (int n = 1; n <= 5; ++n) {
		if (n <= count) {
			[attributedStar appendAttributedString:lightStar];
		} else {
			[attributedStar appendAttributedString:darkStar];
		}
	}
	return [[NSAttributedString alloc] initWithAttributedString:attributedStar];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (tableView.tag == 1) {
		return self.leftCellDataArray.count;
	} else if (tableView.tag == 2) {
		return self.rightCellDataArray.count;
	}
	return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (tableView.tag == 1) {
		TableViewCellData *data = self.leftCellDataArray[indexPath.row];
		return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
	} else if (tableView.tag == 2) {
		TableViewCellData *data = self.rightCellDataArray[indexPath.row];
		return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
	}
	return nil;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (tableView.tag == 2) {
		TableViewCellData *data = self.rightCellDataArray[indexPath.row];
		return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
	}
	return [UIConstants defaultTableViewRowHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (tableView.tag == 1) {
		TableViewCellData *data = self.leftCellDataArray[indexPath.row];
		[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
	} else if (tableView.tag == 2) {
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		TableViewCellData *data = self.rightCellDataArray[indexPath.row];
		[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
	}
}

@end
