//
// BusStatusEditViewController.m
// Project
//
// Created by Ziv on 16/3/16.
//
//

#import "BusStatusEditViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "NavigationItemSheet.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/A2DynamicDelegate.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "WebService.h"
#import "Vars.h"

@interface BusStatusEditViewController ()

@property (nonatomic, strong) NSMutableArray *cellDataArrays;

@property (nonatomic, strong) NSArray *busStatusList;
@property (nonatomic, strong) NSArray *cancelledTypeList;
@property (nonatomic, strong) NSArray *hourList;
@property (nonatomic, strong) NSArray *minuteList;

@property (nonatomic, assign) NSInteger statu;
@property (nonatomic, assign) NSInteger cancelledType;
@property (nonatomic, strong) NSString *note;
@property (nonatomic, assign) NSInteger selectedHours;
@property (nonatomic, assign) NSInteger selectedMins;

@property (nonatomic, readonly, strong) NSString *delayedTime;

@end

@implementation BusStatusEditViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.busStatusList = @[@3, @2, @4, @1];
	self.cancelledTypeList = @[@1, @2, @3, @4];
	self.hourList = @[@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12];
	self.minuteList = @[@0, @5, @10, @15, @20, @25, @30, @35, @40, @45, @50, @55];

	self.statu = self.busStatusInfo.status;
	self.cancelledType = self.busStatusInfo.cancelled_type;
	self.selectedHours = self.busStatusInfo.hour;
	self.selectedMins = self.busStatusInfo.min;
	self.note = self.busStatusInfo.note;

	if (self.statu == 1) {
		self.statu = 2;
	}
	if (self.cancelledType == 0) {
		self.cancelledType = 1;
	}

	if (YES) {
		UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight] + 2 * 15)];
		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:@"Submit" forState:UIControlStateNormal];
		[button addTarget:self action:@selector(submitBusStatus) forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:button];
		[footerView addSubview:button];
		self.tableView.tableFooterView = footerView;
	}
	[self buildCellDataSource];
}

#pragma mark - Action

- (void)submitBusStatus {
	if (![self validateSubmit]) {
		return;
	}
	if ([[BusStatusInfo nameForStatus:self.statu] isEqualToString:@"Cancelled"]) {
		[CocoaUtils showConfirmWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:@"You will cancel %@ on %@. This action will also close the ticket sales.", self.busStatusInfo.product.name, self.busStatusInfo.service_date] dismissalHandler:^{
			[self changeBusStatus];
		}];
	} else {
		[self changeBusStatus];
	}
}

- (void)configDatePickerOnTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
	UIPickerView *pickerView = [[UIPickerView alloc] init];

	[pickerView.bk_dynamicDataSource implementMethod:@selector(numberOfComponentsInPickerView:) withBlock:^NSInteger (UIPickerView *pickerView) {
		return 2;
	}];
	[pickerView.bk_dynamicDataSource implementMethod:@selector(pickerView:numberOfRowsInComponent:) withBlock:^NSInteger (UIPickerView *pickerView, NSInteger component) {
		if (component == 0) {
			return self.hourList.count;
		} else if (component == 1) {
			return self.minuteList.count;
		}
		return 0;
	}];
	pickerView.dataSource = pickerView.bk_dynamicDataSource;
	[pickerView.bk_dynamicDelegate implementMethod:@selector(pickerView:titleForRow:forComponent:) withBlock:^NSString *(UIPickerView *pickerView, NSInteger row, NSInteger component) {
		if (component == 0) {
			if (row == 0) {
				return @"Select";
			} else {
				return [self.hourList[row] stringValue];
			}
		} else if (component == 1) {
			if (row == 0) {
				return @"Select";
			} else {
				return [self.minuteList[row] stringValue];
			}
		}
		return nil;
	}];
	pickerView.delegate = pickerView.bk_dynamicDelegate;

	[pickerView selectRow:[self.hourList indexOfObject:@(self.selectedHours)]  inComponent:0 animated:YES];
	[pickerView selectRow:[self.minuteList indexOfObject:@(self.selectedMins)]  inComponent:1 animated:YES];

	NavigationItemSheet *sheet = [[NavigationItemSheet alloc] initWithViews:@[pickerView] handler:^{
		self.selectedHours = [self.hourList[[pickerView selectedRowInComponent:0]] intValue];
		self.selectedMins = [self.minuteList[[pickerView selectedRowInComponent:1]] intValue];
		[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
	}];
	[sheet show];
}

#pragma mark - Network

- (void)changeBusStatus {
	ChangeBusStatus *changeBusStatus = [[ChangeBusStatus alloc] init];
	changeBusStatus.scheduleId = [NSString stringWithFormat:@"%d", self.busStatusInfo.pid];
	changeBusStatus.departureDate = self.busStatusInfo.service_date;
	changeBusStatus.status = self.statu;
	changeBusStatus.note = self.note;
	changeBusStatus.hour = self.selectedHours;
	changeBusStatus.min = self.selectedMins;
	changeBusStatus.cancelledType = self.cancelledType;

	NSDictionary *requestDict = [Utility perlParamXml:[changeBusStatus innerXML] action:changeBusStatus.name];

	[Utility getXMLFromRequestWithMethod:@"GET" url:changeBusStatus.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		// NSLog(@"%@", jsonDict);
		if (![mapper parseWithJSONObject:jsonDict]) {
			WebServiceResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				self.busStatusInfo.status = self.statu;
				self.busStatusInfo.cancelled_type = self.cancelledType;
				self.busStatusInfo.hour = self.selectedHours;
				self.busStatusInfo.min = self.selectedMins;
				self.busStatusInfo.note = self.note;
				[self.busStatusInfo trim];
				NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
				[notificationCenter postNotificationName:BusStatusDidEditingNotification object:nil];
				[self.navigationController popViewControllerAnimated:YES];
			}
		}
	}];
}

#pragma mark - Property

- (NSString *)delayedTime {
	return self.selectedHours != 0 || self.selectedMins != 0 ? [BusStatusInfo timeStringOfHour:self.selectedHours andMinute:self.selectedMins] : @"Select Hour, Select Minute";
}

#pragma mark - Private

- (BOOL)validateSubmit {
	[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 NO;
			}
		}
	}
	return YES;
}

- (void)buildCellDataSource {
	self.cellDataArrays = [NSMutableArray array];
	@weakify(self)
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.showsRequiredAsteriskDuringEditing = YES;
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
		[data setTextBlock:^NSString *{
			@strongify(self)
			return [BusStatusInfo nameForStatus:self.statu];
		}];
		data.detailText = @"New Status";
		data.detailTextColor = [UIColor lightGrayColor];
		data.editingType = TableViewCellEditingTypePickerView;
		data.observedObject = self;
		data.keyPath = @"statu";
		data.optionValues = self.busStatusList;
		data.optionTexts = [self.busStatusList bk_map:^NSString *(NSNumber *statu) {
			return [BusStatusInfo nameForStatus:statu.intValue];
		}];
		[data setValueChangedPostActionBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, id editingControl) {
			@strongify(self)
			[self updateTableViewCellDataArrayForNewStatus];
			[tableView reloadData];
		}];
		self.cellDataArrays[0] = @[data];
	}
	[self updateTableViewCellDataArrayForNewStatus];
}

- (void)updateTableViewCellDataArrayForNewStatus {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	if (self.statu == 3) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.showsRequiredAsteriskDuringEditing = YES;
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
		[data setTextBlock:^NSString *{
			@strongify(self)
			return [BusStatusInfo reasonForCancelledType:self.cancelledType];
		}];
		data.detailText = @"Reason";
		data.detailTextColor = [UIColor lightGrayColor];
		data.editingType = TableViewCellEditingTypePickerView;
		data.observedObject = self;
		data.keyPath = @"cancelledType";
		data.optionValues = self.cancelledTypeList;
		data.optionTexts = [self.cancelledTypeList bk_map:^NSString *(NSNumber *cancelledType) {
			return [BusStatusInfo reasonForCancelledType:cancelledType.intValue];
		}];
		[data setValueChangedPostActionBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, id editingControl) {
			@strongify(self)
			[self updateTableViewCellDataArrayForNewCancelledType];
			[tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
		}];
		[array addObject:data];
	} else if (self.statu == 2) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.showsRequiredAsteriskDuringEditing = YES;
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
		[data setTextBlock:^NSString *{
			@strongify(self)
			return self.delayedTime;
		}];
		data.detailText = @"Delayed Time";
		data.detailTextColor = [UIColor lightGrayColor];
		[data setRequiredValidationRuleBlock:^BOOL {
			@strongify(self)
			return self.selectedHours != 0 || self.selectedMins != 0;
		}];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self configDatePickerOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	} else if (self.statu == 4) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.showsRequiredAsteriskDuringEditing = YES;
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
		[data setTextBlock:^NSString *{
			@strongify(self)
			return self.delayedTime;
		}];
		data.detailText = @"Departed early time";
		data.detailTextColor = [UIColor lightGrayColor];
		[data setRequiredValidationRuleBlock:^BOOL {
			@strongify(self)
			return self.selectedHours != 0 || self.selectedMins != 0;
		}];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self configDatePickerOnTableView: tableView atIndexPath: indexPath];
		}];
		[array addObject:data];
	}
	self.cellDataArrays[1] = array;
	[self updateTableViewCellDataArrayForNewCancelledType];
}

- (void)updateTableViewCellDataArrayForNewCancelledType {
	NSMutableArray *array = self.cellDataArrays[1];
	[CocoaUtils removeObjectsInArray:array fromIndex:1];
	@weakify(self)
	if (self.statu != 3 || self.cancelledType == 4) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.detailText = @"Note to customers";
		data.detailTextColor = [UIColor lightGrayColor];
		data.editingType = TableViewCellEditingTypeTextField;
		data.autocapitalizationType = UITextAutocapitalizationTypeSentences;
		data.observedObject = self;
		data.keyPath = @"note";
		[data addIntegrityValidationRuleBlock:^BOOL {
			@strongify(self)
			return [Utility canBeConvertedToUrlEncodedFromString:self.note];
		} withMessageBlock:^NSString *{
			return IMLocalizedString(@"Please enter alphabetic characters only");
		}];
		[array addObject:data];
	}
}

#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];
}

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

#pragma mark - Table view delegate

- (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
