//
// TrackBusStatusViewController.m
// LiveProject
//
// Created by Ziv on 15/7/29.
//
//

#import "TrackBusStatusViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "UIConstants.h"
#import "ComboBoxViewController.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "TrackBusStatusResponseJsonMapper.h"
#import "BusStatusInfoResultViewController.h"
#import "Vars.h"

@interface TrackBusStatusViewController ()

@property (nonatomic, strong) NSMutableArray *cellDataArrays;

@property (nonatomic, assign) BOOL isByCities;
@property (nonatomic, strong) NSString *scheduleIdText;
@property (nonatomic, strong) NSString *departureText;
@property (nonatomic, strong) NSString *arrivalText;
@property (nonatomic, strong) NSString *departureDateText;

@property (nonatomic, strong, readonly) NSArray *availableDates;

@end

static NSString *const defaultScheduleIDPlaceholder = @"Bus ID";
static NSString *const defaultDepartureCityPlaceholder = @"Departure City";
static NSString *const defaultArrivalCityPlaceholder = @"Arrival City";

@implementation TrackBusStatusViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.departureDateText = [[DateFormatUtils ISO_DATE_FORMAT] format:[NSDate date]];

	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 Bus ID", @"By Cities", 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.isByCities ? 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(checkStatus) 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 - Property

- (NSArray *)availableDates {
	return [CocoaUtils continuousDatesInRange:NSMakeRange(0, 7) ofUnit:NSCalendarUnitDay forDate:[DateUtils addDays:[NSDate date] amount:-3]];
}

#pragma mark - Action

- (void)changeLR:(UISegmentedControl *)segmentControl {
	if (segmentControl.selectedSegmentIndex == 0) {
		self.isByCities = NO;
	} else {
		self.isByCities = YES;
	}
	[self updateTableViewCellDataArrayForCitiesOrID];
	[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)checkStatus {
	if (![self validateBusStatus]) {
		return;
	}
	BusStatusInfoResultViewController *viewController = [[BusStatusInfoResultViewController alloc] init];
	viewController.isByCities = self.isByCities;
	viewController.scheduleIdText = self.scheduleIdText;
	viewController.departureText = self.departureText;
	viewController.arrivalText = self.arrivalText;
	viewController.departureDateText = self.departureDateText;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Segue

- (void)performSegueForDepartureCityOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	NSArray *departures = [Vars appDelegate].coreData.busDepartureArrivalPairs.allKeys;
	ComboBoxViewController *viewController = [[ComboBoxViewController alloc] init];
	viewController.title = defaultDepartureCityPlaceholder;
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.suggestionTitle = @"Popular";
	[viewController setItemsWithArray:departures];
	[viewController suggestValues:[Vars appDelegate].coreData.busSearchDataSource[@"hot_departures"]];
	[viewController setDidSelectItemBlock:^(ComboBoxItem *item) {
		[self.navigationController popViewControllerAnimated:YES];
		self.departureText = item.value;
		if ([[Vars appDelegate].coreData.busDepartureArrivalPairs[self.departureText] count] == 1) {
			self.arrivalText = [[Vars appDelegate].coreData.busDepartureArrivalPairs[self.departureText] firstObject];
		} else {
			self.arrivalText = nil;
		}
		[tableView reloadRowsAtIndexPaths:@[indexPath, [CocoaUtils nextIndexPath: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.departureText]) {
		[viewController selectValue:self.departureText];
	}
	[self.navigationController pushViewController:viewController animated:YES];
}

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

#pragma mark - Private

- (void)buildCellDataSource {
	self.cellDataArrays = [NSMutableArray array];
	[self updateTableViewCellDataArrayForCitiesOrID];
	@weakify(self)
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
			[data setTextBlock:^NSString *{
				@strongify(self)
				return [StringUtils isEmpty:self.departureDateText] ? @"Departure Date" : [CocoaUtils localizedStringFromDate:[[DateFormatUtils ISO_DATE_FORMAT] parse:self.departureDateText] template:@"EEEMdd"];
			}];
			[data setTextColorBlock:^UIColor *{
				@strongify(self)
				return [StringUtils isEmpty:self.departureDateText] ? [UIColor lightGrayColor] : [Vars defaultTintColor];
			}];
			data.editingType = TableViewCellEditingTypePickerView;
			data.observedObject = self;
			data.keyPath = @"departureDateText";
			data.optionTexts = [self.availableDates bk_map:^id (id obj) {
				return [CocoaUtils localizedStringFromDate:obj template:@"EEEMdd"];
			}];
			data.optionValues = [self.availableDates bk_map:^id (id obj) {
				return [[DateFormatUtils ISO_DATE_FORMAT] format:obj];
			}];
			[array addObject:data];
		}
		self.cellDataArrays[1] = [NSArray arrayWithArray:array];
	}
}

- (void)updateTableViewCellDataArrayForCitiesOrID {
	@weakify(self)
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (self.isByCities) {
			if (YES) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
				[data setTextBlock:^NSString *{
					@strongify(self)
					return ![StringUtils isEmpty:self.departureText] ? self.departureText : defaultDepartureCityPlaceholder;
				}];
				[data setTextColorBlock:^UIColor *{
					@strongify(self)
					return ![StringUtils isEmpty:self.departureText] ? [Vars defaultTintColor] : [UIColor lightGrayColor];
				}];
				data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
				data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
				data.validationMessageCaption = defaultDepartureCityPlaceholder;
				[data setRequiredValidationRuleBlock:^BOOL {
					@strongify(self)
					return ![StringUtils isEmpty:self.departureText];
				}];
				[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
					@strongify(self)
					[self performSegueForDepartureCityOnTableView: tableView atIndexPath:indexPath];
				}];
				[array addObject:data];
			}
			if (YES) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
				[data setTextBlock:^NSString *{
					@strongify(self)
					return ![StringUtils isEmpty:self.arrivalText] ? self.arrivalText : defaultArrivalCityPlaceholder;
				}];
				[data setTextColorBlock:^UIColor *{
					@strongify(self)
					return ![StringUtils isEmpty:self.arrivalText] ? [Vars defaultTintColor] : [UIColor lightGrayColor];
				}];
				data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
				data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
				data.validationMessageCaption = defaultArrivalCityPlaceholder;
				[data setRequiredValidationRuleBlock:^BOOL {
					@strongify(self)
					return ![StringUtils isEmpty:self.arrivalText];
				}];
				[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
					@strongify(self)
					[self performSegueForArrivalCityOnTableView: tableView atIndexPath:indexPath];
				}];
				[array addObject:data];
			}
		} else {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.editingType = TableViewCellEditingTypeTextField;
			data.observedObject = self;
			data.keyPath = @"scheduleIdText";
			data.placeholder = defaultScheduleIDPlaceholder;
			data.isEditingRequired = YES;
			[data addIntegrityValidationRuleBlock:^BOOL {
				@strongify(self)
				return [Utility canBeConvertedToUrlEncodedFromString:self.scheduleIdText];
			} withMessageBlock:^NSString *{
				return IMLocalizedString(@"Please enter alphabetic characters only");
			}];
			[array addObject:data];
		}
		self.cellDataArrays[0] = [NSArray arrayWithArray:array];
	}
}

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

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return self.cellDataArrays.count;
}

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

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

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	if (section == 1) {
		return [UIConstants defaultTableViewSectionHeight:UITableViewStylePlain];
	}
	return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if (section == 1) {
		return IMLocalizedString(@"Departure Date");
	}
	return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

@end
