//
// CheckInSearchViewController.m
// LiveProject
//
// Created by Ziv on 15/7/6.
//
//

#import "CheckInSearchViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "NavigationItemSheet.h"
#import "PrivacyUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "CustomLeftRightTitleToolbar.h"
#import "UIViewController+Privilege.h"
#import "BusRouteSelectionViewProvider.h"
#import "BusProductSelectionViewProvider.h"
#import "ProductSelectionViewProvider.h"
#import "CheckInScanViewController.h"
#import "SoldStockListViewController.h"
#import "Vars.h"

@interface CheckInSearchViewController ()

@property (nonatomic, assign) BOOL isSelectedBus;
@property (nonatomic, strong) BusRouteSelectionViewProvider *routeProvider;
@property (nonatomic, strong) BusRoute *busRoute;
@property (nonatomic, strong) BusProductSelectionViewProvider *busProvider;
@property (nonatomic, strong) Product *busProduct;
@property (nonatomic, strong) ProductSelectionViewProvider *showProvider;
@property (nonatomic, strong) Product *showProduct;
@property (nonatomic, assign) NSInteger product_id;
@property (nonatomic, strong) NSDate *serviceDate;

@property (nonatomic, strong) CustomLeftRightTitleToolbar *datePickerToolbar;

@property (nonatomic, strong) NSArray *cellDataArray;

@end

static NSString *const defaultRoutePlaceholder = @"Route";
static NSString *const defaultSchedulePlaceholder = @"Schedule";
static NSString *const defaultShowPlaceholder = @"Show";

@implementation CheckInSearchViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.serviceDate = [NSDate date];

	if ([Vars appDelegate].loginUser.sell_bus) {
		self.isSelectedBus = YES;
	}
	if (YES) {
		UIView *headerView = [[UIView alloc] init];
		if ([Vars appDelegate].loginUser.sell_bus && [Vars appDelegate].loginUser.sell_show) {
			self.isSelectedBus = YES;
			UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"Bus", @"Show"]];
			segmentedControl.selectedSegmentIndex = self.isSelectedBus ? 0 : 1;
			[segmentedControl addTarget:self action:@selector(changedLR:) forControlEvents:UIControlEventValueChanged];
			[headerView addSubview:segmentedControl];
		}
		if (YES) {
			@weakify(self)
			self.datePickerToolbar = [[CustomLeftRightTitleToolbar alloc] init];
			[self.datePickerToolbar setLeftBarButtonItemHandler:^{
				@strongify(self)
				[self backwardDate];
			}];
			[self.datePickerToolbar setRightBarButtonItemHandler:^{
				@strongify(self)
				[self forwardDate];
			}];
#if TARGET_IPHONE_SIMULATOR
			self.datePickerToolbar.titleBarButtonItem.enabled = YES;
			[self.datePickerToolbar setTitleBarButtonItemHandler:^{
				@strongify(self)
				[self accessDatePicker];
			}];
#else
			self.datePickerToolbar.titleBarButtonItem.enabled = NO;
#endif
			[self checkDateStepButton];
			[Utility addRoundedBorderToView:self.datePickerToolbar];
			[headerView addSubview:self.datePickerToolbar];
		}
		[CocoaUtils autoVerticalAlignmentToSubviews:headerView.subviews spacing:15];
		headerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height);
		self.tableView.tableHeaderView = headerView;
	}
	if (YES) {
		UIView *footerView = [[UIView alloc] init];
		if ([Vars appDelegate].loginUser.availableMetadataObjectType) {
			UIButton *scanButton = [UIButton buttonWithType:UIButtonTypeSystem];
			scanButton.backgroundColor = [Vars defaultTintColor];
			scanButton.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
			[scanButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
			[scanButton setTitle:@"Scan QR Code" forState:UIControlStateNormal];
			[scanButton addTarget:self action:@selector(clickScan) forControlEvents:UIControlEventTouchUpInside];
			[Utility addRoundedBorderToButton:scanButton];
			[footerView addSubview:scanButton];
			[scanButton autoSetDimension:ALDimensionHeight toSize:[UIConstants defaultTableViewRowHeight]];
		}
		if (YES) {
			UIButton *listButton = [UIButton buttonWithType:UIButtonTypeSystem];
			listButton.backgroundColor = [Vars defaultTintColor];
			listButton.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
			[listButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
			[listButton setTitle:@"View Customer List" forState:UIControlStateNormal];
			[listButton addTarget:self action:@selector(clickList) forControlEvents:UIControlEventTouchUpInside];
			[Utility addRoundedBorderToButton:listButton];
			[footerView addSubview:listButton];
			[listButton autoSetDimension:ALDimensionHeight toSize:[UIConstants defaultTableViewRowHeight]];
		}
		[CocoaUtils autoVerticalAlignmentToSubviews:footerView.subviews spacing:15];
		footerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [footerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height);
		self.tableView.tableFooterView = footerView;
	}
	[self buildCellDataSource];

	if ([Vars appDelegate].loginUser.products) {
		[self configureProviders];
	}
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	if (![Vars appDelegate].loginUser.products) {
		[[Vars appDelegate] prefetchLoginPostData:^{
			[self configureProviders];
		}];
	}
}

#pragma mark - Action

- (void)changedLR:(UISegmentedControl *)sender {
	if (sender.selectedSegmentIndex == 0) {
		self.isSelectedBus = YES;
	} else {
		self.isSelectedBus = NO;
	}
	UIButton *mapButton = [self.tableView.tableFooterView viewWithTag:NSStringFromClass([UIButton class]).hash];
	mapButton.hidden = !self.isSelectedBus;
	[self buildCellDataSource];
	[self.tableView reloadData];
}

- (void)clickScan {
	if (![self validateSubmit]) {
		return;
	}
	if (!TARGET_IPHONE_SIMULATOR && ![PrivacyUtils authorizeCamera]) {
		[CocoaUtils showConfirmWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please allow \"%@\" to access your camera"), [CocoaUtils bundleName]] otherActionTitle:IMLocalizedString(@"Open Settings") otherActionHandler:^{
			[CocoaUtils openSettings];
		}];
		return;
	}
	CheckInScanViewController *viewController = [[CheckInScanViewController alloc] init];
	viewController.product_id = self.product_id;
	viewController.service_date = [[DateFormatUtils ISO_DATE_FORMAT] format:self.serviceDate];
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)clickList {
	if (![self validateSubmit]) {
		return;
	}
	SoldStockListViewController *viewController = [[SoldStockListViewController alloc] init];
	viewController.allowsCheckIn = YES;
	viewController.isCheckIn = YES;
	viewController.product_id = self.product_id;
	viewController.date_type = 1;
	viewController.startDate = [[DateFormatUtils ISO_DATE_FORMAT] format:self.serviceDate];
	viewController.endDate = [[DateFormatUtils ISO_DATE_FORMAT] format:self.serviceDate];
	viewController.inputCustomerName = @"";
	viewController.inputCn = @"";
	viewController.email = @"";
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Property

- (NSInteger)product_id {
	if (_product_id > 0) {
		return _product_id;
	}
	Product *product = self.isSelectedBus ? self.busProduct : self.showProduct;
	if (product) {
		return product.product_id;
	}
	return 0;
}

#pragma mark - Segue

#pragma mark - Private

- (void)buildCellDataSource {
	@weakify(self)
	NSMutableArray *array = [NSMutableArray array];
	if (self.isSelectedBus) {
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			[data setTextBlock:^NSString *{
				@strongify(self)
				return self.busRoute ? self.busRoute.bus_route_name : defaultRoutePlaceholder;
			}];
			[data setTextColorBlock:^UIColor *{
				@strongify(self)
				return self.busRoute ? [Vars defaultTintColor] : [UIColor lightGrayColor];
			}];
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
			data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
			data.validationMessageCaption = defaultRoutePlaceholder;
			[data setRequiredValidationRuleBlock:^BOOL {
				@strongify(self)
				return self.busRoute;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				UITableViewController *viewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
				viewController.title = defaultRoutePlaceholder;
				viewController.tableView.delegate = self.routeProvider;
				viewController.tableView.dataSource = self.routeProvider;
				[self.routeProvider tableView:viewController.tableView selectBusRoute:self.busRoute];
				[self.navigationController pushViewController:viewController animated:YES];
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			[data setTextBlock:^NSString *{
				@strongify(self)
				return self.busProduct ? self.busProduct.listingDepartureTime : defaultSchedulePlaceholder;
			}];
			[data setTextColorBlock:^UIColor *{
				@strongify(self)
				return self.busProduct ? [Vars defaultTintColor] : [UIColor lightGrayColor];
			}];
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
			data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
			data.validationMessageCaption = defaultSchedulePlaceholder;
			[data setRequiredValidationRuleBlock:^BOOL {
				@strongify(self)
				return self.busProduct;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (!self.busRoute) {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:@"Please select %@ first", defaultRoutePlaceholder.lowercaseString]];
					return;
				}
				UITableViewController *viewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
				viewController.title = defaultSchedulePlaceholder;
				viewController.tableView.delegate = self.busProvider;
				viewController.tableView.dataSource = self.busProvider;
				[self.busProvider tableView:viewController.tableView selectProduct:self.busProduct];
				[self.navigationController pushViewController:viewController animated:YES];
			}];
			[array addObject:data];
		}
	} else {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		[data setTextBlock:^NSString *{
			@strongify(self)
			return self.showProduct ? self.showProduct.name : defaultShowPlaceholder;
		}];
		[data setTextColorBlock:^UIColor *{
			@strongify(self)
			return self.showProduct ? [Vars defaultTintColor] : [UIColor lightGrayColor];
		}];
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		data.validationMessageCaption = defaultShowPlaceholder;
		[data setRequiredValidationRuleBlock:^BOOL {
			@strongify(self)
			return self.showProduct;
		}];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			UITableViewController *viewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
			viewController.title = defaultShowPlaceholder;
			viewController.tableView.delegate = self.showProvider;
			viewController.tableView.dataSource = self.showProvider;
			[self.showProvider tableView:viewController.tableView selectProduct:self.showProduct];
			[self.navigationController pushViewController:viewController animated:YES];
		}];
		[array addObject:data];
	}
#if TARGET_IPHONE_SIMULATOR
	TableViewCellData *data = [[TableViewCellData alloc] init];
	data.editingType = TableViewCellEditingTypeTextField;
	[data setEditingDidEndPostActionBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, UITextField *textField) {
		@strongify(self)
		self.product_id = textField.text.integerValue;
	}];
	[array addObject:data];
#endif
	self.cellDataArray = [NSArray arrayWithArray:array];
}

- (void)configRouteProvider {
	@weakify(self)
	self.routeProvider = [[BusRouteSelectionViewProvider alloc] initWithBusRoutes:[Vars appDelegate].loginUser.busRoutes];
	[self.routeProvider didFocusBusRoute:^(BusRoute *busRoute) {
		@strongify(self)
		self.busRoute = busRoute;
		[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
		//
		NSArray *pids = [[busRoute.pids_string componentsSeparatedByString:@","] valueForKeyPath:@"integerValue"];
		[self.busProvider reloadProducts:[[Vars appDelegate].loginUser.products bk_select:^BOOL (Product *obj) {
			return obj.is_bus && [pids containsObject:@(obj.product_id)];
		}]];
		[self.busProvider autoFocus];
	}];
	[self.routeProvider didSelectBusRoute:^(BusRoute *busRoute) {
		@strongify(self)
		[self.navigationController popViewControllerAnimated: YES];
	}];
}

- (void)configBusProvider {
	@weakify(self)
	self.busProvider = [[BusProductSelectionViewProvider alloc] init];
	[self.busProvider didFocusProduct:^(Product *product) {
		@strongify(self)
		self.busProduct = product;
		[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
	}];
	[self.busProvider didSelectProduct:^(Product *product) {
		@strongify(self)
		[self.navigationController popViewControllerAnimated: YES];
	}];
}

- (void)configShowProvider {
	@weakify(self)
	self.showProvider = [[ProductSelectionViewProvider alloc] initWithProducts:[[Vars appDelegate].loginUser.products bk_select:^BOOL (Product *obj) {
		return obj.is_show;
	}]];
	[self.showProvider didFocusProduct:^(Product *product) {
		@strongify(self)
		self.showProduct = product;
		[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
	}];
	[self.showProvider didSelectProduct:^(Product *product) {
		@strongify(self)
		[self.navigationController popViewControllerAnimated: YES];
	}];
}

- (void)configureProviders {
	if ([Vars appDelegate].loginUser.sell_bus) {
		[self configRouteProvider];
		[self configBusProvider];
	}
	if ([Vars appDelegate].loginUser.sell_show) {
		[self configShowProvider];
	}
}

- (BOOL)validateSubmit {
	[self.tableView endEditing:YES];
	if (self.product_id > 0) {
		return YES;
	}
	for (int row = 0; row < [self.cellDataArray count]; row++) {
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
		TableViewCellData *data = self.cellDataArray[indexPath.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;
}

- (void)backwardDate {
	self.serviceDate = [DateUtils addDays:self.serviceDate amount:-1];
	[self checkDateStepButton];
}

- (void)forwardDate {
	self.serviceDate = [DateUtils addDays:self.serviceDate amount:1];
	[self checkDateStepButton];
}

#if TARGET_IPHONE_SIMULATOR

- (void)accessDatePicker {
	UIDatePicker *datePicker = [[UIDatePicker alloc] init];
	datePicker.datePickerMode = UIDatePickerModeDate;
	NavigationItemSheet *sheet = [[NavigationItemSheet alloc] initWithViews:@[datePicker] handler:^{
		self.serviceDate = datePicker.date;
		[self checkDateStepButton];
	}];
	[sheet show];
}

#endif

- (void)checkDateStepButton {
	NSDate *minDate = [DateUtils addDays:[NSDate date] amount:-1];
	NSDate *maxDate = [DateUtils addDays:[NSDate date] amount:1];
	self.datePickerToolbar.leftBarButtonItem.enabled = [DateUtils truncated:self.serviceDate compareTo:minDate unit:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay] == NSOrderedDescending;
	self.datePickerToolbar.rightBarButtonItem.enabled = [DateUtils truncated:self.serviceDate compareTo:maxDate unit:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay] == NSOrderedAscending;
	self.datePickerToolbar.titleBarButtonItem.title = [Utility localizedStringWithDate:self.serviceDate];
}


#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 {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	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
