//
// BusCheckInViewController.m
// Project
//
// Created by ziv on 2017/7/26.
//
//

#import "SelfCheckInSearchViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "ComboBoxViewController.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <FontAwesomeKit/FontAwesomeKit.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "TicketStatusApi.h"
#import "SelfCheckInPageResponseJsonMapper.h"
#import "BusCheckInViewController.h"
#import "Vars.h"

@interface SelfCheckInSearchViewController ()

@property (nonatomic, strong) NSArray *cellDataArray;

@property (nonatomic, assign) BOOL isByDepartureCity;
@property (nonatomic, strong) NSString *CN;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *departureCity;

@end

@implementation SelfCheckInSearchViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	if (YES) {
		UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultSegmentedControlHeight] + 15 * 2)];
		UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"By Last Name", @"By Departure City", nil]];
		segmentControl.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultSegmentedControlHeight]);
		[segmentControl addTarget:self action:@selector(changeLR:) forControlEvents:UIControlEventValueChanged];
		segmentControl.selectedSegmentIndex = self.isByDepartureCity ? 1 : 0;
		[headerView addSubview:segmentControl];
		self.tableView.tableHeaderView = headerView;
	}
	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:@"Search" forState:UIControlStateNormal];
		[button addTarget:self action:@selector(performActionForSelfCheckInPage) 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"];
}

#pragma mark - Action

- (void)changeLR:(UISegmentedControl *)segmentControl {
	if (segmentControl.selectedSegmentIndex == 0) {
		self.isByDepartureCity = NO;
	} else {
		self.isByDepartureCity = YES;
	}
	[self buildCellDataSource];
	[self.tableView reloadData];
}

- (void)performActionForSelfCheckInPage {
	if ([self validateSearchCriteria]) {
		[self performRequestForSelfCheckInPage];
	}
}

#pragma mark - Network

- (void)performRequestForSelfCheckInPage {
	SelfCheckInPage *selfCheckInPage = [[SelfCheckInPage alloc] init];
	selfCheckInPage.confirmationNumber = self.CN;
	if (self.isByDepartureCity) {
		selfCheckInPage.departureCity = self.departureCity;
	} else {
		selfCheckInPage.lastName = self.lastName;
	}

	NSDictionary *requestDict = [BeanUtils describeAccessible:selfCheckInPage];

	[Utility performRESTRequestWithMethod:@"POST" url:selfCheckInPage.address parameters:requestDict success:^(id jsonObject) {
		// NSLog(@"%@", jsonObject);
		SelfCheckInPageResponseJsonMapper *mapper = [[SelfCheckInPageResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]) {
			SelfCheckInPageResponse *response = mapper.response;
			if (response.soldStock) {
				SoldStock *stock = response.soldStock;

				Product *product = [[Product alloc] init];
				product.busRouteName = stock.scheduleName;

				SalesEntry *entry = [[SalesEntry alloc] init];
				entry.service_date = stock.service_date;
				entry.product = product;
				entry.stocks = @[stock];

				User *user = [[User alloc] init];
				user.block_status = stock.blockStatus;

				Sales *order = [[Sales alloc] init];
				order.user = user;
				order.entries = @[entry];

				// NSLog(@"%d %@ %@ %@ %d %@ %@ %@ %d", stock.stock_id, stock.sold_to_name, stock.cn, stock.boarding_number, stock.vendor_checkin,  stock.desc, product.busRouteName, entry.service_date, user.block_status);

				[self performSegueForSelfCheckInWithSalesEntry:entry];
			}
		}
	}];
}

#pragma mark - Segue

- (void)performSegueForSelfCheckInWithSalesEntry:(SalesEntry *)entry {
	BusCheckInViewController *viewController = [[BusCheckInViewController alloc] init];
	viewController.entry = entry;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (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 setItemsWithArray:[Vars appDelegate].coreData.busDepartureArrivalPairs.allKeys];
	[viewController suggestValues:[Vars appDelegate].coreData.busSearchDataSource[@"hot_departures"]];
	[viewController setDidSelectItemBlock:^(ComboBoxItem *item) {
		[self.navigationController popViewControllerAnimated:YES];
		self.departureCity = item.value;
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	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.departureCity]) {
		[viewController selectValue:self.departureCity];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.editingType = TableViewCellEditingTypeTextField;
		data.placeholder = @"CN";
		data.observedObject = self;
		data.keyPath = @"CN";
		data.allowsPlaceholderFloating = YES;
		data.isEditingRequired = YES;
		[array addObject:data];
	}
	if (self.isByDepartureCity) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		[data setTextBlock:^NSString *{
			@strongify(self)
			return [StringUtils isEmpty:self.departureCity] ? @"Departure City" : self.departureCity;
		}];
		[data setTextColorBlock:^UIColor *{
			@strongify(self)
			return [StringUtils isEmpty:self.departureCity] ? [UIColor lightGrayColor] : [UIColor blackColor];
		}];
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForDepartureCityOnTableView: tableView atIndexPath: indexPath];
		}];
		data.validationMessageCaption = @"Departure City";
		[data setRequiredValidationRuleBlock:^BOOL {
			@strongify(self)
			return ![StringUtils isEmpty:self.departureCity];
		}];
		[array addObject:data];
	} else {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.editingType = TableViewCellEditingTypeTextField;
		data.placeholder = @"Last Name";
		data.observedObject = self;
		data.keyPath = @"lastName";
		data.allowsPlaceholderFloating = YES;
		data.isEditingRequired = YES;
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

- (BOOL)validateSearchCriteria {
	[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 {
	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];
}

#pragma mark - Public

+ (UIImage *)imageForSelfCheckInIcon {
	FAKIcon *maleIcon = [FAKIonIcons manIconWithSize:16];
	maleIcon.drawingPositionAdjustment = UIOffsetMake(-12, 4);
	FAKIcon *busIcon = [FAKFontAwesome busIconWithSize:22];
	FAKIcon *checkCircleIcon = [FAKFontAwesome checkCircleIconWithSize:12];
	checkCircleIcon.drawingPositionAdjustment = UIOffsetMake(10, -10);
	return [UIImage imageWithStackedIcons:@[maleIcon, checkCircleIcon, busIcon] imageSize:CGSizeMake(32, 32)];
}

@end
