#import "SalesEntryDetailViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "Collectors.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "MapViewController.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "TextViewController.h"
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "BusStop.h"
#import "Label.h"
#import "SalesEntryRoom.h"
#import "SoldStock.h"
#import "PerlWS.h"
#import "UIViewController+Privilege.h"
#import "GetETicketsResponseJsonMapper.h"
#import "GetReschedulePolicyResponseJsonMapper.h"
#import "GetItineraryByIdResponseJsonMapper.h"
#import "PurchaseRecordResponseJsonMapper.h"
#import "BusSearchDetailPriceCell.h"
#import "CustomDualSubtitleRightCircleCell.h"
#import "BusStatusDetailViewController.h"
#import "BusVendorReviewDetailViewController.h"
#import "ReschedulePolicyViewController.h"
#import "BusCheckInViewController.h"
#import "SoldStockBarcodeViewController.h"
#import "Vars.h"

@interface SalesEntryDetailViewController ()
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) Sales *templeorder;
@end

@implementation SalesEntryDetailViewController

- (instancetype)init {
	if (self = [super init]) {
		// Custom initialization
		self.title = IMLocalizedString(@"Details");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	
	if ([StringUtils isEmpty:self.itineraryId]) {
		if ([self.entry.service_date compare:[[DateFormatUtils ISO_DATE_FORMAT] format:[NSDate date]]] != NSOrderedAscending) {
			NSMutableString *string = [NSMutableString string];
			[string im_appendString:IMLocalizedString(@"Details")];
			[string im_appendString:IMLocalizedString(WORD_DIVIDER_SPACE)];
			[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_LEFT)];
			[string im_appendString:self.entry.status_name];
			[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_RIGHT)];
			self.title = [NSString stringWithString:string];
			[self buildCellDataSource];
		}
		
	} else {
		[self getEntryDetailById:self.itineraryId];
	}
	
	NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
	[notificationCenter addObserver:self selector:@selector(performNotificationForSelfCheckIn) name:SelfCheckInDidEditingNotification object:nil];
	
	self.tableView.sectionHeaderHeight = [UIConstants defaultTableViewCellLayoutInsets].top;
	self.tableView.sectionFooterHeight = [UIConstants defaultTableViewCellLayoutInsets].bottom;
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CustomDualSubtitleRightCircleCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([CustomDualSubtitleRightCircleCell class])];
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BusSearchDetailPriceCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([BusSearchDetailPriceCell class])];
}

#pragma mark - Notification

- (void)performNotificationForSelfCheckIn {
	[self.tableView reloadData];
}

#pragma mark - Network
- (void)getEntryDetailById:(NSString *)itinerId{
	GetItineraryById *getItiner = [[GetItineraryById alloc] init];
	getItiner.itineraryId = itinerId;
	NSDictionary *requestDict = [Utility perlParamXml:[getItiner innerXML] action:getItiner.name];
	// NSLog(@"%@", requestDict);
	[Utility getXMLFromRequestWithMethod:@"GET" url:getItiner.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		GetItineraryByIdResponseJsonMapper *mapper = [[GetItineraryByIdResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetItineraryByIdResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				if (response.orders.count != 0) {
					Sales *order = response.orders[0];
					if (order.entries.count != 0) {
						self.entry = order.entries[0];
						self.templeorder = order;
						[self buildCellDataSource];
						[self.tableView reloadData];
					}
				}
			}
		}
		
	}];
}


- (void)getETicketByEntry {
	GetETicketByEntry *eTicketByEntry = [[GetETicketByEntry alloc] init];
	eTicketByEntry.entry_id = self.entry.entry_id;

	NSDictionary *requestDict = [Utility perlParamXml:[eTicketByEntry innerXML] action:eTicketByEntry.name];
	[Utility getXMLFromRequestWithMethod:@"GET" url:eTicketByEntry.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		GetETicketsResponseJsonMapper *mapper = [[GetETicketsResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetETicketsResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else if (response.etickets.count > 0) {
				_ETicket *eticket = response.etickets.firstObject;
				IMWebViewController *viewController = [[IMWebViewController alloc] initWithHTMLString:eticket.html];
				viewController.title = IMLocalizedString(@"E-Ticket");
				[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
				viewController.autoshrink = YES;
				[self.navigationController pushViewController:viewController animated:YES];
			}
		}
	}];
}

- (void)getOrderSummaryByOrder {
	GetOrderSummaryByOrder *orderSummary = [[GetOrderSummaryByOrder alloc] init];
	orderSummary.order_code = self.entry.order.order_code;

	NSDictionary *requestDict = [Utility perlParamXml:[orderSummary innerXML] action:orderSummary.name];
	[Utility getXMLFromRequestWithMethod:@"GET" url:orderSummary.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		GetETicketsResponseJsonMapper *mapper = [[GetETicketsResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetETicketsResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else if (response.order_summary) {
				IMWebViewController *viewController = [[IMWebViewController alloc] initWithHTMLString:response.order_summary.html];
				viewController.title = IMLocalizedString(@"Order Summary");
				[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
				viewController.autoshrink = YES;
				[self.navigationController pushViewController:viewController animated:YES];
			}
		}
	}];
}

#pragma mark - Segue

- (void)performSegueForDetailWithSoldStock:(SoldStock *)stock {
	SoldStockBarcodeViewController *viewController = [[SoldStockBarcodeViewController alloc] init];
	viewController.stock = stock;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForBusStops:(NSArray *)stops withLabel:(Label *)label {
	MapViewController *viewController = [[MapViewController alloc] init];
	viewController.title = label.name;
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	[viewController addAnnotations:[BusStop toAnnotations:stops]];
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForBusStatusDetails {
	BusStatusDetailViewController *viewController = [[BusStatusDetailViewController alloc] init];
	viewController.departureDate = self.entry.service_date;
	viewController.product = self.entry.product;
	[self.navigationController pushViewController:viewController animated:YES];
}

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

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

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

- (void)performSegueForReviewFinish {
	TextViewController *viewController = [[TextViewController alloc] init];
	viewController.title = @"Share your experience";
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.textView.attributedText = [BusVendorReviewDetailViewController attributedFinishTextWithOverallRating:self.entry.review_overall_rating byVendorName:self.entry.product.vendor_obj.short_name];
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *arrays = [NSMutableArray array];
	@weakify(self)
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = self.entry.shortDescription;
			[array addObject:data];
		}
		if (YES) {
			NSMutableArray *objs = [NSMutableArray array];
			if (self.entry.rooms.count > 0) {
				for (SalesEntryRoom *room in self.entry.rooms) {
					[objs addObject:room];
					if (!room.checkin_guest) {
						[objs addObjectsFromArray:room.stocks];
					}
				}
			} else {
				[objs addObjectsFromArray:self.entry.stocks];
			}
			for (id obj in objs) {
				if ([obj class] == [SalesEntryRoom class]) {
					SalesEntryRoom *room = obj;
					if (YES) {
						TableViewCellData *data = [[TableViewCellData alloc] init];
						data.text = room.shortDescription;
						if (self.entry.product.is_hotel) {
							data.style = UITableViewCellStyleSubtitle;
							data.detailText = [self.entry peopleDescriptionAtRoomNo:room.room_no];
							data.detailTextColor = [UIColor lightGrayColor];
						}
						[array addObject:data];
					}
					if (room.room_type) {
						TableViewCellData *data = [[TableViewCellData alloc] init];
						data.style = UITableViewCellStyleSubtitle;
						data.text = room.room_type;
						data.detailText = IMLocalizedString(@"Room Type");
						data.detailTextColor = [UIColor lightGrayColor];
						[array addObject:data];
					}
					if (room.check_in && room.check_out) {
						TableViewCellData *data = [[TableViewCellData alloc] init];
						data.reuseIdentifier = NSStringFromClass([CustomDualSubtitleRightCircleCell class]);
						data.weaklyAssociatedObject = room;
						[data setNeedLayoutFittingHeight];
						[array addObject:data];
					}
					if (room.checkin_guest) {
						TableViewCellData *data = [[TableViewCellData alloc] init];
						data.style = UITableViewCellStyleSubtitle;
						data.text = room.checkin_guest.hotelDescription;
						data.detailText = IMLocalizedString(@"Check-in Guest");
						data.detailTextColor = [UIColor lightGrayColor];
						data.allowsTextLineWrapping = YES;
						[array addObject:data];
					}
					if (room.reservation_number) {
						TableViewCellData *data = [[TableViewCellData alloc] init];
						data.style = UITableViewCellStyleSubtitle;
						data.text = room.reservation_number;
						data.detailText = IMLocalizedString(@"Reservation Number");
						data.detailTextColor = [UIColor lightGrayColor];
						[array addObject:data];
					}
					if (room.record_locator) {
						TableViewCellData *data = [[TableViewCellData alloc] init];
						data.style = UITableViewCellStyleSubtitle;
						data.text = room.record_locator;
						data.detailText = IMLocalizedString(@"Record Locator");
						data.detailTextColor = [UIColor lightGrayColor];
						[array addObject:data];
					}
				} else if ([obj class] == [SoldStock class]) {
					SoldStock *stock = obj;
					TableViewCellData *data = [[TableViewCellData alloc] init];
					data.style = UITableViewCellStyleSubtitle;
					data.text = stock.sold_to_name;
					[data setDetailTextBlock:^NSString *{
						return stock.otherShortDescription;
					}];
					if (![StringUtils isEmpty:stock.barcode]) {
						if (self.allowsShowBarcode) {
							[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
								FAKIcon *metacodeIcon = [self.entry.product.vendor_obj.availableMetadataObjectType isEqualToString:AVMetadataObjectTypeQRCode] ? [FAKFontAwesome qrcodeIconWithSize:32] : [FAKFontAwesome barcodeIconWithSize:32];
								FAKIcon *checkmarkIcon = [FAKFontAwesome checkIconWithSize:24];
								[checkmarkIcon addAttribute:NSForegroundColorAttributeName value:[UIColor cloverColor]];
								return [[UIImageView alloc] initWithImage:stock.vendor_checkin ? [UIImage imageWithStackedIcons:@[metacodeIcon, checkmarkIcon] imageSize:CGSizeMake(32, 32)] : [DrawUtils imageWithFAKIcon:metacodeIcon fillColor:[UIColor blackColor]]];
							}];
							if (self.entry.product.vendor_obj.availableCodeGenerator) {
								[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
									@strongify(self)
									[self performSegueForDetailWithSoldStock:stock];
								}];
							}
						} else {
							[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
								UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:stock.vendor_checkin ? @"icon_bus_boarding_yes" : @"icon_bus_boarding_no"]];
								return imageView;
							}];
						}
					}
					[array addObject:data];
				}
			}
		}
		[arrays addObject:[NSArray arrayWithArray: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 (!self.entry.product.is_hotel) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.localizedDepartureDateString;
			data.detailText = IMLocalizedString(@"Departure Date");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		for (Label *label in self.entry.optionalLabels) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.attributedText = [self.entry getOptionAttributedText:label.alias withFont:[UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle]];
			data.detailText = label.name;
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			if (self.allowsShowMap) {
				if ([label.alias isEqualToString:@"departure"] && self.entry.departureStops.count > 0) {
					[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
						return [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:24] fillColor:[Vars defaultTintColor]]];
					}];
					[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
						@strongify(self)
						[self performSegueForBusStops: self.entry.departureStops withLabel:label];
					}];
				} else if ([label.alias isEqualToString:@"arrival"] && self.entry.arrivalStops.count > 0) {
					[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
						return [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:24] fillColor:[Vars defaultTintColor]]];
					}];
					[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
						@strongify(self)
						[self performSegueForBusStops: self.entry.arrivalStops withLabel:label];
					}];
				}
			}
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.itinerary_id;
			data.detailText = IMLocalizedString(@"Itinerary ID");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = [@"$" stringByAppendingFormat:@"%g", self.entry.sold_amount];
			data.detailText = IMLocalizedString(@"Payment");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.status_name;
			data.detailText = IMLocalizedString(@"Status");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (self.entry.bus_status_info.status > 0) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusSearchDetailPriceCell class]);
			data.weaklyAssociatedObject = self.entry.bus_status_info;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForBusStatusDetails];
			}];
			[data setNeedLayoutFittingHeight];
			[array addObject:data];
		}
		if (self.entry.product.schedule_id) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.product.schedule_id;
			data.detailText = IMLocalizedString(@"Bus ID");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (self.entry.product.is_bus) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.product.vendor_obj.short_name;
			data.detailText = IMLocalizedString(@"Operator");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.order.order_code;
			data.detailText = IMLocalizedString(@"Order ID");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.order.localizedPurchaseDateString;
			data.detailText = IMLocalizedString(@"Purchase Date");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (self.entry.order.entries.count > 1) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = [@"$" stringByAppendingFormat:@"%g", [[self.entry.order.entries valueForKeyPath:@"@sum.sold_amount"] floatValue]];
			data.detailText = IMLocalizedString(@"Total Payment");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (self.entry.order.customer_name) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.order.customer_name;
			data.detailText = IMLocalizedString(@"Purchaser");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (self.entry.order.customer_home_phone) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.order.customer_home_phone;
			data.detailText = IMLocalizedString(@"Phone");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (self.entry.order.customer_email) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.order.customer_email;
			data.detailText = IMLocalizedString(@"Email");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (self.entry.product.is_bus && !self.entry.cancelled && self.allowsSelfCheckIn) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = @"Self Check-In";
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForSelfCheckIn];
			}];
			[array addObject:data];
		}
		if (self.entry.product.is_bus && self.allowsSelfReschedule && self.entry.enable_reschedule) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = @"Self Reschedule";
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForReschedulePolicy];
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"View Order Summary");
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self getOrderSummaryByOrder];
			}];
			[array addObject:data];
		}
		if (self.entry.enable_eticket_send) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"View E-Ticket");
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self getETicketByEntry];
			}];
			[array addObject:data];
		}
		if (self.entry.enable_review_write) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"Write a Review");
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.entry.review_overall_rating > 0) {
					[self performSegueForReviewFinish];
				} else {
					[self performSegueForReviewEditing];
				}
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}

	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

#pragma mark - Table view methods

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

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.cellDataArrays[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomDualSubtitleRightCircleCell class])]) {
		return [UIToolkit instantiateRowHeightForTableViewCellWithNibName:NSStringFromClass([CustomDualSubtitleRightCircleCell class])];
	} else if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomDualSubtitleRightCircleCell class])]) {
		return [UIToolkit instantiateRowHeightForTableViewCellWithNibName:NSStringFromClass([BusSearchDetailPriceCell class])];
	}
	return [UIConstants defaultTableViewRowHeight];
}

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

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomDualSubtitleRightCircleCell class])]) {
		CustomDualSubtitleRightCircleCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomDualSubtitleRightCircleCell class])];
		SalesEntryRoom *room = data.weaklyAssociatedObject;
		cell.topTitleLabel.text = [Utility localizedStringWithStandardDateString:room.check_in];
		cell.topSubtitleLabel.text = IMLocalizedString(@"Check-in Date");
		cell.bottomTitleLabel.text = [Utility localizedStringWithStandardDateString:room.check_out];
		cell.bottomSubtitleLabel.text = IMLocalizedString(@"Check-out Date");
		cell.circleLabel.text = [NSString stringWithFormat:room.nights > 1 ? IMLocalizedString(@"%d\nnights") : IMLocalizedString(@"%d\nnight"), room.nights];
		return cell;
	} else if ([data.reuseIdentifier isEqualToString:NSStringFromClass([BusSearchDetailPriceCell class])]) {
		BusSearchDetailPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BusSearchDetailPriceCell class])];
		BusStatusInfo *info = data.weaklyAssociatedObject;
		cell.titleLabel.text = info.statusName;
		cell.titleLabel.textColor = info.statusColor;
		cell.subtitleLabel.text = IMLocalizedString(@"Bus Status");
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.detailDisclosureButton.hidden = YES;
		[cell.detailDisclosureButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
		if (![StringUtils isEmpty:info.otherDescription]) {
			cell.detailDisclosureButton.hidden = NO;
			[cell.detailDisclosureButton bk_addEventHandler:^(id sender) {
				UIButton *button = sender;
				[CocoaUtils showTooltipWithMessage:info.otherDescription inView:self.view atFrame:[sender convertRect:button.bounds toView:self.view]];
			} forControlEvents:UIControlEventTouchUpInside];
		}
		return cell;
	}
	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];
}

#pragma mark

- (void)dealloc {
	NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
	[notificationCenter removeObserver:self name:SelfCheckInDidEditingNotification object:nil];
}

@end
