//
// BusRescheduleViewController.m
// GotoBus
//
// Created by haibara on 1/22/15.
//
//

#import "BusRescheduleViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "NetUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/A2DynamicDelegate.h>
#import <BlocksKit/NSObject+A2DynamicDelegate.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "CartEntry.h"
#import "Label.h"
#import "SoldStock.h"
#import "PerlWS.h"
#import "PurchaseRecordViewController.h"
#import "FinishRescheduleResponseJsonMapper.h"
#import "PaymentInfoViewController.h"
#import "ProductSearchListVC.h"
#import "SalesEntryDetailViewController.h"
#import "Vars.h"

@interface BusRescheduleViewController ()
@property (nonatomic, strong) CartEntry *bookingEntry;
@property (nonatomic, strong) NSMutableArray<NSArray *> *cellDataArrays;
@property (nonatomic, strong) CheckRescheduleFeeResponse *checkRescheduleFeeResponse;
@end

@implementation BusRescheduleViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.bookingEntry = [[CartEntry alloc] init];
	self.bookingEntry.product = self.entry.product;
	self.bookingEntry.stocks = [NSMutableArray arrayWithArray:self.entry.stocks];

	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:@"Submit" forState:UIControlStateNormal];
		@weakify(self)
		[button bk_addEventHandler:^(id sender) {
			@strongify(self)
			if ([self validateReschedule]) {
				[self finishReschedule:nil];
			}
		} forControlEvents: UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:button];
		[footerView addSubview:button];
		self.tableView.tableFooterView = footerView;
	}
	self.tableView.sectionHeaderHeight = [UIConstants defaultTableViewCellLayoutInsets].top;
	self.tableView.sectionFooterHeight = [UIConstants defaultTableViewCellLayoutInsets].bottom;
	[self buildCellDataSource];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];

	if ([Vars appDelegate].shopCarts.entries.count > 0) {
		CartEntry *entry = [Vars appDelegate].shopCarts.entries.firstObject;
		self.bookingEntry.product = entry.product;
		self.bookingEntry.options = entry.options;
		self.checkRescheduleFeeResponse = nil;
		[self updateTableViewCellDataArrayForReschedule];
		[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
	}
}

#pragma mark - Network

- (void)checkRescheduleFee {
	CheckRescheduleFee *checkRescheduleFee = [[CheckRescheduleFee alloc] init];
	checkRescheduleFee.orderCode = self.entry.order.order_code;
	if (self.bookingEntry.product != self.entry.product) {
		checkRescheduleFee.transferredOut = [WebService transferredOutWithCartEntry:self.bookingEntry reason:1 service_fee:0 penalty:0];
		checkRescheduleFee.transferredIn = [WebService transferredInWithCartEntry:self.bookingEntry];
	} else {
		checkRescheduleFee.transferredOut = [WebService transferredOutWithCartEntry:self.bookingEntry];
	}

	NSDictionary *requestDict = [Utility perlParamXml:[checkRescheduleFee innerXML] action:checkRescheduleFee.name];
	// NSLog(@"%@", requestDict);
	[Utility getXMLFromRequestWithMethod:@"POST" url:checkRescheduleFee.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[CheckRescheduleFeeResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			CheckRescheduleFeeResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				self.checkRescheduleFeeResponse = response;
				NSIndexPath *indexPath = [CocoaUtils indexPathOfObjectIdenticalTo:[CocoaUtils objectPassingTest:^BOOL (TableViewCellData *obj, NSUInteger idx, BOOL *stop) {
					return [obj.identifier isEqualToString:@"checkRescheduleFee"];
				} fromArray:self.cellDataArrays[2]] fromArray:self.cellDataArrays[2] inSection:2];
				if (indexPath) {
					[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
				}
			}
		}
	}];
}

- (void)finishReschedule:(_PaymentInfo *)paymentInfo {
	FinishReschedule *finishReschedule = [[FinishReschedule alloc] init];
	finishReschedule.orderCode = self.entry.order.order_code;
	if (self.bookingEntry.product != self.entry.product) {
		finishReschedule.transferredOut = [WebService transferredOutWithCartEntry:self.bookingEntry reason:1 service_fee:0 penalty:0];
		finishReschedule.transferredIn = [WebService transferredInWithCartEntry:self.bookingEntry];
	} else {
		finishReschedule.transferredOut = [WebService transferredOutWithCartEntry:self.bookingEntry];
	}
	finishReschedule.paymentInfo = paymentInfo;

	NSDictionary *requestDict = [Utility perlParamXml:[finishReschedule innerXML] action:finishReschedule.name];
	// NSLog(@"%@", requestDict);
	[Utility getXMLFromRequestWithMethod:@"POST" url:finishReschedule.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		FinishRescheduleResponseJsonMapper *mapper = [[FinishRescheduleResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			FinishRescheduleResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else if (![StringUtils isEmpty:response.order_code]) {
				[self myBookings];
			} else if (response.paymentInfo) {
				_PaymentInfo *paymentInfo = response.paymentInfo;
				PaymentInfoViewController *viewController = [[PaymentInfoViewController alloc] init];
				viewController.paymentInfo = paymentInfo;
				[viewController setDestructiveBlock:^{
					[self finishReschedule:paymentInfo];
				}];
				[self.navigationController pushViewController:viewController animated:YES];
			}
		}
	}];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *arrays = [NSMutableArray array];
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			if (self.entry.busRouteName) {
				data.text = self.entry.busRouteName;
			} else {
				data.style = UITableViewCellStyleSubtitle;
				data.text = self.entry.product.name;
				data.detailText = IMLocalizedString(@"Product");
				data.detailTextColor = [UIColor lightGrayColor];
				data.allowsTextLineWrapping = YES;
			}
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = [Utility localizedStringWithStandardDateString:self.entry.service_date];
			data.detailText = IMLocalizedString(@"Departure Date");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.attributedText = [self.entry getOptionAttributedText:@"departure" withFont:[UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle]];
			data.detailText = @"Departure";
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.attributedText = [self.entry getOptionAttributedText:@"arrival" withFont:[UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle]];
			data.detailText = @"Arrival";
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
		if ([self.entry hasOption:@"priceType"]) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.attributedText = [self.entry getOptionAttributedText:@"priceType" withFont:[UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle]];
			data.detailText = @"Ticket Type";
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = [@"$" stringByAppendingFormat:@"%g", self.entry.sold_amount];
			data.detailText = @"Original Payment";
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		@weakify(self)
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = self.entry.shortDescription;
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				@strongify(self)
				if (self.bookingEntry.stocks.count == self.entry.stocks.count) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.bookingEntry.stocks.count == self.entry.stocks.count) {
					[self.bookingEntry.stocks removeAllObjects];
				} else {
					[self.bookingEntry.stocks removeAllObjects];
					[self.bookingEntry.stocks addObjectsFromArray:self.entry.stocks];
				}
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		for (SoldStock *stock in self.entry.stocks) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = stock.sold_to_name;
			data.detailText = stock.otherShortDescription;
			[data setAccessoryTypeBlock:^UITableViewCellAccessoryType {
				@strongify(self)
				if ([self.bookingEntry.stocks containsObject:stock]) {
					return UITableViewCellAccessoryCheckmark;
				}
				return UITableViewCellAccessoryNone;
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if ([self.bookingEntry.stocks containsObject:stock]) {
					[self.bookingEntry.stocks removeObject:stock];
				} else {
					[self.bookingEntry.stocks addObject:stock];
				}
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = arrays;
	[self updateTableViewCellDataArrayForReschedule];
}

- (void)updateTableViewCellDataArrayForReschedule {
	@weakify(self)
	NSMutableArray *array = [NSMutableArray array];
	if (self.bookingEntry.product != self.entry.product) {
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = [Utility localizedStringWithStandardDateString:[self.bookingEntry.options[@"date"] substringToIndex:10]];
			data.textColor = [Vars defaultTintColor];
			data.detailText = @"New Departure Date";
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.bookingEntry.options[@"departure"];
			data.textColor = [Vars defaultTintColor];
			data.detailText = @"New Departure";
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.bookingEntry.options[@"arrival"];
			data.textColor = [Vars defaultTintColor];
			data.detailText = @"New Arrival";
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
	} else if (self.entry.enable_bus_stop_change) {
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			[data setAttributedTextBlock:^NSAttributedString *{
				@strongify(self)
				UIFont *font = [UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle];
				NSString *option_value = self.bookingEntry.options[@"departure"];
				if ([StringUtils isEmpty:option_value]) {
					return [[NSAttributedString alloc] im_initWithString:@"New Departure" attributes:@{ NSFontAttributeName : font }];
				} else {
					return [Utility attributedStringWithHtmlString:option_value fixAttributes:@{ NSFontAttributeName : font }];
				}
			}];
			[data setTextColorBlock:^UIColor *{
				@strongify(self)
				return [StringUtils isEmpty:self.bookingEntry.options[@"departure"]] ? [CocoaUtils colorWithRGBs:StandardColorOrange] : [Vars defaultTintColor];
			}];
			[data setDetailTextBlock:^NSString *{
				@strongify(self)
				return [StringUtils isEmpty:self.bookingEntry.options[@"departure"]] ? nil : @"New Departure";
			}];
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
			data.editingType = TableViewCellEditingTypePickerView;
			data.observedObject = self.bookingEntry.options;
			data.keyPath = @"departure";
			data.optionTexts = [[self.entry.datedDepartureStops valueForKeyPath:@"option_value"] bk_map:^id (id obj) {
				return [CocoaUtils stripHtmlString:obj];
			}];
			data.optionValues = [self.entry.datedDepartureStops valueForKeyPath:@"option_value"];
			[data setShouldSelectBlock:^BOOL (UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.bookingEntry.stocks.count == 0) {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select passenger(s) first"];
					return NO;
				}
				return YES;
			}];
			[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
				@strongify(self)
				return [NSString stringWithFormat:@"%u", [self.bookingEntry.options[@"departure"] length]];
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			[data setAttributedTextBlock:^NSAttributedString *{
				@strongify(self)
				UIFont *font = [UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle];
				NSString *option_value = self.bookingEntry.options[@"arrival"];
				if ([StringUtils isEmpty:option_value]) {
					return [[NSAttributedString alloc] im_initWithString:@"New Arrival" attributes:@{ NSFontAttributeName : font }];
				} else {
					return [Utility attributedStringWithHtmlString:option_value fixAttributes:@{ NSFontAttributeName : font }];
				}
			}];
			[data setTextColorBlock:^UIColor *{
				@strongify(self)
				return [StringUtils isEmpty:self.bookingEntry.options[@"arrival"]] ? [CocoaUtils colorWithRGBs:StandardColorOrange] : [Vars defaultTintColor];
			}];
			[data setDetailTextBlock:^NSString *{
				@strongify(self)
				return [StringUtils isEmpty:self.bookingEntry.options[@"arrival"]] ? nil : @"New Arrival";
			}];
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
			data.editingType = TableViewCellEditingTypePickerView;
			data.observedObject = self.bookingEntry.options;
			data.keyPath = @"arrival";
			data.optionTexts = [[self.entry.datedArrivalStops valueForKeyPath:@"option_value"] bk_map:^id (id obj) {
				return [CocoaUtils stripHtmlString:obj];
			}];
			data.optionValues = [self.entry.datedArrivalStops valueForKeyPath:@"option_value"];
			[data setShouldSelectBlock:^BOOL (UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.bookingEntry.stocks.count == 0) {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select passenger(s) first"];
					return NO;
				}
				return YES;
			}];
			[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
				@strongify(self)
				return [NSString stringWithFormat:@"%u", [self.bookingEntry.options[@"arrival"] length]];
			}];
			[array addObject:data];
		}
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		if (self.bookingEntry.product != self.entry.product) {
			data.text = self.bookingEntry.product.busRouteName ? self.bookingEntry.product.busRouteName : self.bookingEntry.product.name;
			data.textColor = [Vars defaultTintColor];
		} else {
			data.text = @"New Schedule";
			data.textColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
		}
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
		data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			if (self.bookingEntry.stocks.count == 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select passenger(s) first"];
				return;
			}
			NSArray *bus_from_cities = [self.bookingEntry.stocks valueForKeyPath:@"@distinctUnionOfObjects.departureStop.station.destination.show_name"];
			NSArray *bus_to_cities = [self.bookingEntry.stocks valueForKeyPath:@"@distinctUnionOfObjects.arrivalStop.station.destination.show_name"];
			if (bus_from_cities.count == 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"The departure city isn't available on selected passenger(s)"];
				return;
			}
			if (bus_to_cities.count == 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"The arrival city isn't available on selected passenger(s)"];
				return;
			}
			if (bus_from_cities.count > 1) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"The departure cities are different on selected passenger(s)"];
				return;
			}
			if (bus_to_cities.count > 1) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"The arrival cities are different on selected passenger(s)"];
				return;
			}
			ProductSearchListVC *viewController = [[ProductSearchListVC alloc] init];
			viewController.isReschedule = YES;
			viewController.currentDepartString = self.entry.service_date;
			viewController.departCity = bus_from_cities.firstObject;
			viewController.returnCity = bus_to_cities.firstObject;
			if (!self.entry.enable_advanced_reschedule) {
				viewController.vendorId = self.entry.product.vendor;
				if ([self.entry.stocks bk_any:^BOOL (SoldStock *stock) {
					return [stock.desc[@"priceType"] isEqualToString:@"Flexi Ticket"];
				}]) {
					viewController.isFlexiTicketOnly = YES;
				}
			}
			[self.navigationController pushViewController:viewController animated:YES];
		}];
		if (self.bookingEntry.product != self.entry.product) {
			[array insertObject:data atIndex:0];
		} else {
			[array addObject:data];
		}
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.identifier = @"checkRescheduleFee";
		data.style = UITableViewCellStyleSubtitle;
		[data setTextBlock:^NSString *{
			@strongify(self)
			return [StringUtils isEmpty:self.checkRescheduleFeeResponse.calculate_fee] ? @"Price Difference" : self.checkRescheduleFeeResponse.calculate_fee;
		}];
		[data setTextColorBlock:^UIColor *{
			@strongify(self)
			return [StringUtils isEmpty:self.checkRescheduleFeeResponse.calculate_fee] ? [CocoaUtils colorWithRGBs:StandardColorOrange] : [Vars defaultTintColor];
		}];
		[data setDetailTextBlock:^NSString *{
			@strongify(self)
			return [StringUtils isEmpty:self.checkRescheduleFeeResponse.calculate_fee] ? nil : @"Price Difference";
		}];
		data.detailTextColor = [UIColor lightGrayColor];
		data.allowsTextLineWrapping = YES;
		[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
			return [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome refreshIconWithSize:24] fillColor:[Vars defaultTintColor]]];
		}];
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			if ([self validateReschedule]) {
				[self checkRescheduleFee];
			}
		}];
		[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
			@strongify(self)
			return [NSString stringWithFormat:@"%u", self.checkRescheduleFeeResponse.calculate_fee.length];
		}];
		[array addObject:data];
	}
	self.cellDataArrays[2] = [NSArray arrayWithArray:array];
}

- (BOOL)validateReschedule {
	if (self.bookingEntry.stocks.count == 0) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select passenger(s) first"];
		return NO;
	}
	if (self.bookingEntry.product == self.entry.product && !self.bookingEntry.options[@"departure"] && !self.bookingEntry.options[@"arrival"]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select new departure/arrival/schedule"];
		return NO;
	}
	BOOL diff = NO;
	if (self.bookingEntry.product != self.entry.product) {
		diff = diff || self.bookingEntry.product.product_id != self.entry.product.product_id;
		diff = diff || ![[self.bookingEntry.options[@"date"] substringToIndex:10] isEqualToString:self.entry.service_date];
		diff = diff || [self.bookingEntry.stocks bk_any:^BOOL (SoldStock *stock) {
			return ![stock.desc[@"departure"] isEqualToString:self.bookingEntry.options[@"departure"]];
		}];
		diff = diff || [self.bookingEntry.stocks bk_any:^BOOL (SoldStock *stock) {
			return ![stock.desc[@"arrival"] isEqualToString:self.bookingEntry.options[@"arrival"]];
		}];
	} else {
		if (self.bookingEntry.options[@"departure"]) {
			diff = diff || [self.bookingEntry.stocks bk_any:^BOOL (SoldStock *stock) {
				return ![stock.desc[@"departure"] isEqualToString:self.bookingEntry.options[@"departure"]];
			}];
		}
		if (self.bookingEntry.options[@"arrival"]) {
			diff = diff || [self.bookingEntry.stocks bk_any:^BOOL (SoldStock *stock) {
				return ![stock.desc[@"arrival"] isEqualToString:self.bookingEntry.options[@"arrival"]];
			}];
		}
	}
	if (!diff) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Nothing has been changed"];
		return NO;
	}
	return YES;
}

- (void)myBookings {
	[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Booking has been updated successfully, please dismiss to return \"My Bookings\"" dismissalHandler:^{
		PurchaseRecordViewController *viewController = [CocoaUtils lastViewControllerWithClass:[PurchaseRecordViewController class] onNavigationController:self.navigationController];
		viewController.upcomingOrderList = nil;
		viewController.pastOrderList = nil;
		[self.navigationController popToViewController:viewController animated:YES];
	}];
}

#pragma mark Table view methods

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

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if (section == 0) {
		return @"Original Schedule";
	} else if (section == 2) {
		return @"Change To";
	}
	return nil;
}

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

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

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