//
// SchedulePassengerListViewController.m
// Project
//
// Created by Ziv on 2017/4/17.
//
//

#import "SchedulePassengerListViewController.h"

#import "BeanUtils.h"
#import "CheckInActionHandler.h"
#import "CocoaUtils.h"
#import "CustomerListPageResponseJsonMapper.h"
#import "DZNEmptyDataSetDefault.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "Lang.h"
#import "SDK.h"
#import "ScheduleAPI.h"
#import "SchedulePassengerListCell.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "UIViewController+Privilege.h"
#import "Utility.h"
#import "Vars.h"

#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/BlocksKit.h>
#import <HMSegmentedControl/HMSegmentedControl.h>
#import <PureLayout/PureLayout.h>
#import <libextobjc/EXTScope.h>

@interface SchedulePassengerListViewController () <DZNEmptyDataSetDefault>

@property (nonatomic, strong) NSMutableArray *selectedStocks;

@property (nonatomic, strong) NSArray *cellDataArray;

@property (nonatomic, strong) HMSegmentedControl *segmentControl;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *checkInButton;
@property (nonatomic, strong) UIButton *undoButton;
@property (nonatomic, strong) UIButton *safeButton;
@property (nonatomic, strong) UIButton *likelySafeButton;
@property (nonatomic, strong) UIButton *likelyUnsafeButton;
@property (nonatomic, strong) UIButton *unsafeButton;

@property (nonatomic, copy) void (^didChangeCheckInCountBlock)(NSInteger totalCount, NSInteger checkInCount);

@property (nonatomic, strong, readonly) NSArray *usedStocks;
@property (nonatomic, strong, readonly) NSArray *checkedStocks;
@property (nonatomic, strong, readonly) NSArray *uncheckedStocks;
@property (nonatomic, strong, readonly) NSArray *safeStocks;
@property (nonatomic, strong, readonly) NSArray *likelySafeStocks;
@property (nonatomic, strong, readonly) NSArray *likelyUnsafeStocks;
@property (nonatomic, strong, readonly) NSArray *unsafeStocks;

@end

@implementation SchedulePassengerListViewController

- (instancetype)init {
	if (self = [super init]) {
		self.hidesBottomBarWhenPushed = YES;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	self.title = self.service_date;

	self.fixedHeaderView = self.segmentControl;

	if (self.allowsCheckIn) {

		self.selectedStocks = [NSMutableArray array];

		@weakify(self)
		self.footerView = [[UIView alloc] init];
		self.footerView.backgroundColor = [UIColor whiteColor];

		UILabel *selectLabel = [[UILabel alloc] init];
		selectLabel.text = @"Select";
		selectLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];

		self.safeButton = [self buildFilterButtonWithBlockStatus:1];
		self.likelySafeButton = [self buildFilterButtonWithBlockStatus:2];
		self.likelyUnsafeButton = [self buildFilterButtonWithBlockStatus:3];
		self.unsafeButton = [self buildFilterButtonWithBlockStatus:NSNotFound];

		self.checkInButton = [UIButton buttonWithType:UIButtonTypeCustom];
		self.checkInButton.backgroundColor = [Vars defaultTintColor];
		self.checkInButton.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		[self.checkInButton setTitle:@"Check-In" forState:UIControlStateNormal];
		[self.checkInButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[self.checkInButton setTitleColor:[UIColor groupTableViewBackgroundColor] forState:UIControlStateDisabled];
        [self.checkInButton bk_addEventHandler:^(id sender) {
            @strongify(self)
            if (self.selectedStocks.count > 0) {
                [CheckInActionHandler updateStocks:self.selectedStocks toCheckIn:YES commit:^(NSString *message) {
                    [self reloadSegmentTitles];
                    [self updateSelectedStocks];
                    [self buildCellDataSource];
                    [self.tableView reloadData];
                    [self reloadSelectionToolbar];
                    [self changeCheckInCount];
                } rollback:^(NSString *message) {
                    [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:message];
                }];
            } else {
                [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select passenger(s) first"];
            }
        } forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:self.checkInButton];

		self.undoButton = [UIButton buttonWithType:UIButtonTypeCustom];
		self.undoButton.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
		[self.undoButton setTitle:@"Undo" forState:UIControlStateNormal];
		[self.undoButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
		[self.undoButton setTitleColor:[UIColor groupTableViewBackgroundColor] forState:UIControlStateDisabled];
		[DrawUtils addRoundedBorderToRect:self.undoButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[Vars defaultTintColor]];
		[self.undoButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			if (self.selectedStocks.count > 0) {
				[CheckInActionHandler updateStocks:self.selectedStocks toCheckIn:NO commit:^(NSString *message) {
					[self reloadSegmentTitles];
					[self updateSelectedStocks];
					[self buildCellDataSource];
					[self.tableView reloadData];
					[self reloadSelectionToolbar];
					[self changeCheckInCount];
				}];
			} else {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select passenger(s) first"];
			}
		} forControlEvents:UIControlEventTouchUpInside];

		[self.footerView addSubview:selectLabel];
		[self.footerView addSubview:self.safeButton];
		[self.footerView addSubview:self.likelySafeButton];
		[self.footerView addSubview:self.likelyUnsafeButton];
		[self.footerView addSubview:self.unsafeButton];
		[self.footerView addSubview:self.checkInButton];
		[self.footerView addSubview:self.undoButton];

		[selectLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:[UIConstants defaultTableViewCellLayoutInsets].left];

		[self.safeButton autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:selectLabel withOffset:[UIConstants defaultTableViewCellLayoutInsets].left];
		[self.safeButton autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:[UIConstants defaultTableViewCellLayoutInsets].top];
		[self.safeButton autoAlignAxis:ALAxisHorizontal toSameAxisOfView:selectLabel];

		[self.likelySafeButton autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:[UIConstants defaultTableViewCellLayoutInsets].right];
		[self.likelySafeButton autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.safeButton];

		[self.likelyUnsafeButton autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.safeButton];
		[self.likelyUnsafeButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.safeButton withOffset:[UIConstants defaultTableViewCellLayoutInsets].top];

		[self.unsafeButton autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.likelySafeButton];
		[self.unsafeButton autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.likelyUnsafeButton];

		[self.checkInButton autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:[UIConstants defaultTableViewCellLayoutInsets].left];
		[self.checkInButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.likelyUnsafeButton withOffset:[UIConstants defaultTableViewCellLayoutInsets].top];
		[self.checkInButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:[UIConstants defaultTableViewCellLayoutInsets].bottom];
		[self.checkInButton autoSetDimension:ALDimensionHeight toSize:[UIConstants defaultButtonHeight]];

		[self.undoButton autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.checkInButton withOffset:5];
		[self.undoButton autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.checkInButton];
		[self.undoButton autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.checkInButton];
		[self.undoButton autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:[UIConstants defaultTableViewCellLayoutInsets].right];
		[self.undoButton autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.checkInButton];

		self.footerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [self.footerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height);
		self.fixedFooterView = self.footerView;
	} else {
		UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
		NSMutableAttributedString *text = [[NSMutableAttributedString alloc] init];
		[text appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome userIconWithSize:font.pointSize] fillColor:[User colorForBlockStatus:1]]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:[User nameForBlockStatus:1] attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor]}]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"  "]];
		[text appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome userIconWithSize:font.pointSize] fillColor:[User colorForBlockStatus:2]]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:[User nameForBlockStatus:2] attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor]}]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"  "]];
		[text appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome userIconWithSize:font.pointSize] fillColor:[User colorForBlockStatus:3]]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:[User nameForBlockStatus:3] attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor]}]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"  "]];
		[text appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome userIconWithSize:font.pointSize] fillColor:[User colorForBlockStatus:4]]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:[User nameForBlockStatus:4] attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor]}]];

		UILabel *label = [[UILabel alloc] init];
		label.font = font;
		label.attributedText = text;
		[label sizeToFit];

		UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight(label.frame) + [UIConstants defaultTableViewCellLayoutInsets].top + [UIConstants defaultTableViewCellLayoutInsets].bottom)];
		footerView.backgroundColor = [UIColor whiteColor];
		[footerView addSubview:label];
		[label autoCenterInSuperview];

		self.fixedFooterView = footerView;
	}
	self.tableView.emptyDataSetSource = self;
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SchedulePassengerListCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SchedulePassengerListCell class])];

	self.editing = self.allowsCheckIn;

	if (self.soldStocks) {
		self.segmentControl.selectedSegmentIndex = 0;
		self.segmentControl.indexChangeBlock(self.segmentControl.selectedSegmentIndex);
	}
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	if (!self.soldStocks) {
		[self getCustomerList];
	}
}

#pragma mark - Property

- (HMSegmentedControl *)segmentControl {
	if (!_segmentControl) {
		_segmentControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Total", @"Unchecked", @"Check-In"]];
		_segmentControl.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight]);
		_segmentControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
		_segmentControl.selectionIndicatorColor = [Vars defaultTintColor];
		_segmentControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
		@weakify(self)
		[_segmentControl setIndexChangeBlock:^(NSInteger index) {
			@strongify(self)
			[self updateSelectedStocks];
			[self buildCellDataSource];
			[self.tableView reloadData];
			[self reloadSelectionToolbar];
			[self reloadBottomToolbar];
		}];
		[_segmentControl setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
			@strongify(self)
			NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] init];
			[attribute appendAttributedString:[[NSAttributedString alloc] im_initWithString:title attributes:@{NSForegroundColorAttributeName : [UIColor blackColor], NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]}]];
			[attribute appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[attribute appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"%d", [self getCurrentStocksWithIndex:index].count] attributes:@{NSForegroundColorAttributeName : [Vars defaultTintColor], NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]}]];
			return [[NSAttributedString alloc] initWithAttributedString:attribute];
		}];
	}
	return _segmentControl;
}

- (NSArray *)checkedStocks {
	return [self.soldStocks bk_select:^BOOL (SoldStock *stock) {
		return stock.vendor_checkin;
	}];
}

- (NSArray *)uncheckedStocks {
	return [self.soldStocks bk_select:^BOOL (SoldStock *stock) {
		return !stock.vendor_checkin;
	}];
}

- (NSArray *)usedStocks {
	return [self getCurrentStocksWithIndex:self.segmentControl.selectedSegmentIndex];
}

- (NSArray *)safeStocks {
	return [self getFilterStocks:self.usedStocks withBlockStatus:1];
}

- (NSArray *)likelySafeStocks {
	return [self getFilterStocks:self.usedStocks withBlockStatus:2];
}

- (NSArray *)likelyUnsafeStocks {
	return [self getFilterStocks:self.usedStocks withBlockStatus:3];
}

- (NSArray *)unsafeStocks {
	return [self getFilterStocks:self.usedStocks withBlockStatus:NSNotFound];
}

#pragma mark - Network

- (void)getCustomerList {
	CustomerListPage *customerListPage = [[CustomerListPage alloc] init];
	customerListPage.departureDate = self.service_date;
	customerListPage.scheduleStopId = self.scheduleStopId;
    customerListPage.scheduleId  = self.scheduleId;
	customerListPage.isPickUp = self.isPickUp;
	customerListPage.isDropOff = self.isDropOff;
    customerListPage.isDBDSearch = self.isDBDSearch;
    
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:customerListPage];
	self.tableView.emptyDataSetSource = nil;
	[Utility performRESTRequestWithMethod:@"POST" url:customerListPage.address parameters:requestDict success:^(id jsonObject) {
		// NSLog(@"%@", jsonObject);
		CustomerListPageResponseJsonMapper *mapper = [[CustomerListPageResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]) {
			CustomerListPageResponse *response = mapper.response;
			if (response.errorCode > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.errorMessage];
			} else {
				self.soldStocks = response.soldStockList;
				self.segmentControl.selectedSegmentIndex = 0;
				self.tableView.emptyDataSetSource = self;
				self.segmentControl.indexChangeBlock(self.segmentControl.selectedSegmentIndex);
			}
		}
	}];
}

#pragma mark - Action

- (void)changeAccordionActive:(BOOL)active onTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)newIndexPath {
	NSMutableArray *indexPaths = [NSMutableArray array];
	for (int row = 0; row < self.cellDataArray.count; row++) {
		TableViewCellData *data = self.cellDataArray[row];
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
		if ([data.reuseIdentifier isEqualToString:NSStringFromClass([SchedulePassengerListCell class])]) {
			if ([indexPath isEqual:newIndexPath]) {
				data.stronglyAssociatedObject = @(active);
				[indexPaths addObject:newIndexPath];
			} else if (active) {
				if ([data.stronglyAssociatedObject boolValue]) {
					data.stronglyAssociatedObject = @NO;
					if ([tableView.indexPathsForVisibleRows containsObject:indexPath]) {
						[indexPaths addObject:indexPath];
					}
				}
			}
		}
	}
	[tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	for (SoldStock *stock in self.usedStocks) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([SchedulePassengerListCell class]);
		data.weaklyAssociatedObject = stock;
		data.stronglyAssociatedObject = @NO;
		[data setNeedLayoutFittingHeight];
		[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
			return [NSString stringWithFormat:@"%d", [data.stronglyAssociatedObject boolValue]];
		}];
		if (self.editing) {
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (![self.selectedStocks containsObject:stock]) {
					[self.selectedStocks addObject:stock];
				}
				[self reloadSelectionToolbar];
			}];
			[data setDidDeselectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if ([self.selectedStocks containsObject:stock]) {
					[self.selectedStocks removeObject:stock];
				}
				[self reloadSelectionToolbar];
			}];
		}
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

- (void)updateSelectedStocks {
	[self.selectedStocks removeAllObjects];
}

- (void)reloadSegmentTitles {
	[self.segmentControl setNeedsDisplay];
}

- (void)reloadSelectionToolbar {
	NSArray *selectedSafeStocks = [self getFilterStocks:self.selectedStocks withBlockStatus:1];
	NSArray *selectedLikelySafeStocks = [self getFilterStocks:self.selectedStocks withBlockStatus:2];
	NSArray *selectedLikelyUnsafeStocks = [self getFilterStocks:self.selectedStocks withBlockStatus:3];
	NSArray *selectedUnsafeStocks = [self getFilterStocks:self.selectedStocks withBlockStatus:NSNotFound];
	self.safeButton.selected = selectedSafeStocks.count > 0 && selectedSafeStocks.count == self.safeStocks.count;
	self.likelySafeButton.selected = selectedLikelySafeStocks.count > 0 && selectedLikelySafeStocks.count == self.likelySafeStocks.count;
	self.likelyUnsafeButton.selected = selectedLikelyUnsafeStocks.count > 0 && selectedLikelyUnsafeStocks.count == self.likelyUnsafeStocks.count;
	self.unsafeButton.selected = selectedUnsafeStocks.count > 0 && selectedUnsafeStocks.count == self.unsafeStocks.count;
}

- (void)reloadBottomToolbar {

	switch (self.segmentControl.selectedSegmentIndex) {
		case 1:
			self.checkInButton.enabled = YES;
			self.checkInButton.backgroundColor = [Vars defaultTintColor];
			self.undoButton.enabled = NO;
			[DrawUtils addRoundedBorderToRect:self.checkInButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[UIColor clearColor]];
			[DrawUtils addRoundedBorderToRect:self.undoButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:self.undoButton.currentTitleColor];
			break;

		case 2:
			self.checkInButton.enabled = NO;
			self.checkInButton.backgroundColor = [UIColor clearColor];
			self.undoButton.enabled = YES;
			[DrawUtils addRoundedBorderToRect:self.checkInButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:self.checkInButton.currentTitleColor];
			[Utility addRoundedBorderToView:self.undoButton];
			break;

		default:
			self.checkInButton.enabled = YES;
			self.checkInButton.backgroundColor = [Vars defaultTintColor];
			self.undoButton.enabled = YES;
			[DrawUtils addRoundedBorderToRect:self.checkInButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[UIColor clearColor]];
			[Utility addRoundedBorderToView:self.undoButton];
			break;
	}
}

- (void)changeCheckInCount {
	if (self.didChangeCheckInCountBlock) {
		self.didChangeCheckInCountBlock(self.soldStocks.count, self.checkedStocks.count);
	}
}

- (NSArray *)getCurrentStocksWithIndex:(NSInteger)index {
	switch (index) {
		case 0:
			return self.soldStocks;

		case 1:
			return self.uncheckedStocks;

		case 2:
			return self.checkedStocks;

		default:
			return nil;
	}
}

- (NSArray *)getFilterStocks:(NSArray *)stocks withBlockStatus:(NSInteger)blockStatus {
	if (blockStatus == 1 || blockStatus == 2 || blockStatus == 3) {
		return [stocks bk_select:^BOOL (SoldStock *stock) {
			return stock.blockStatus == blockStatus;
		}];
	} else {
		return [stocks bk_reject:^BOOL (SoldStock *stock) {
			return stock.blockStatus == 1 || stock.blockStatus == 2 || stock.blockStatus == 3;
		}];
	}
}

- (UIButton *)buildFilterButtonWithBlockStatus:(NSInteger)blockStatus {
	UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	button.titleLabel.font = font;
	[button setImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome circleThinIconWithSize:font.lineHeight] fillColor:[UIColor lightGrayColor]] forState:UIControlStateNormal];
	[button setImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome checkCircleIconWithSize:font.lineHeight] fillColor:[Vars defaultTintColor]] forState:UIControlStateSelected];
	NSMutableAttributedString *text = [[NSMutableAttributedString alloc] init];
	[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
	[text appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome userIconWithSize:font.pointSize] fillColor:[User colorForBlockStatus:blockStatus]]];
	[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
	[text appendAttributedString:[[NSAttributedString alloc] im_initWithString:[User nameForBlockStatus:blockStatus]]];
	[button setAttributedTitle:text forState:UIControlStateNormal];
	@weakify(self)
	[button bk_addEventHandler:^(UIButton *sender) {
		@strongify(self)
		sender.selected = !sender.selected;
		[self.selectedStocks removeObjectsInArray:[self getFilterStocks:self.usedStocks withBlockStatus:blockStatus]];
		if (sender.selected) {
			[self.selectedStocks addObjectsFromArray:[self getFilterStocks:self.usedStocks withBlockStatus:blockStatus]];
		}
		[self.tableView reloadData];
	} forControlEvents: UIControlEventTouchUpInside];
	return button;
}

- (void)removeDetailsFromView:(UIView *)detailView {
	for (UIView *view in detailView.subviews) {
		[view removeFromSuperview];
	}
}

- (void)addDetailsToView:(UIView *)detailView withSoldStock:(SoldStock *)stock {
	NSMutableArray<UIView *> *leftViews = [NSMutableArray array];
	NSMutableArray<UIView *> *rightViews = [NSMutableArray array];

	BOOL isValidPhoneNumber = [Utility isValidPhoneNumber:stock.customerHomePhone];
	UIImageView *phoneImgView = [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome phoneIconWithSize:24] fillColor:isValidPhoneNumber ? [Vars defaultTintColor] : [UIColor lightGrayColor]]];
	if (isValidPhoneNumber) {
		[phoneImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] bk_initWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
			[Utility callPhoneNumber:stock.customerHomePhone];
		}]];
		UIButton *phoneButton = [UIButton buttonWithType:UIButtonTypeSystem];
		[phoneButton setTitle:stock.customerHomePhone forState:UIControlStateNormal];
		[phoneButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
		[phoneButton bk_addEventHandler:^(id sender) {
			[Utility callPhoneNumber:stock.customerHomePhone];
		} forControlEvents:UIControlEventTouchUpInside];
		[rightViews addObject:phoneButton];
	} else {
		UILabel *phoneLabel = [[UILabel alloc] init];
		phoneLabel.text = stock.customerHomePhone;
		[rightViews addObject:phoneLabel];
	}
	[leftViews addObject:phoneImgView];

	UIImageView *departureImgView = [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome locationArrowIconWithSize:24] fillColor:[UIColor lightGrayColor]]];
	UILabel *departureLabel = [[UILabel alloc] init];
	departureLabel.text = stock.departure;
	[leftViews addObject:departureImgView];
	[rightViews addObject:departureLabel];

	UIImageView *arrivalImgView = [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:24] fillColor:[UIColor lightGrayColor]]];
	UILabel *arrivalLabel = [[UILabel alloc] init];
	arrivalLabel.text = stock.arrival;
	[leftViews addObject:arrivalImgView];
	[rightViews addObject:arrivalLabel];

	UIImageView *soldDateImgView = [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome calendarIconWithSize:24] fillColor:[UIColor lightGrayColor]]];
	UILabel *soldDateLabel = [[UILabel alloc] init];
	soldDateLabel.text = [CocoaUtils localizedStringFromDate:[[DateFormatUtils ISO_DATETIME_FORMAT] parse:[NSString stringWithFormat:@"%@ %@", [stock.soldDate substringToIndex:10], [stock.soldTime substringFromIndex:11]]] template:@"hmmaEEEMMMdyyyy"];
	[leftViews addObject:soldDateImgView];
	[rightViews addObject:soldDateLabel];

	UIImageView *priceImgView = [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome tagIconWithSize:24] fillColor:[UIColor lightGrayColor]]];
	UILabel *priceLabel = [[UILabel alloc] init];
	priceLabel.text = [@"$" stringByAppendingFormat:@"%g", stock.soldValue];
	[leftViews addObject:priceImgView];
	[rightViews addObject:priceLabel];

	if (![StringUtils isEmpty:stock.creditCardNumber]) {
		UIImageView *creditCardImgView = [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome creditCardIconWithSize:24] fillColor:[UIColor lightGrayColor]]];
		UILabel *creditCardLabel = [[UILabel alloc] init];
		creditCardLabel.text = stock.creditCardNumber;
		[leftViews addObject:creditCardImgView];
		[rightViews addObject:creditCardLabel];
	}

	for (UIView *view in leftViews) {
		[detailView addSubview:view];
	}
	for (UIView *view in rightViews) {
		[detailView addSubview:view];
	}
	[leftViews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
		[obj autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:5];
		[rightViews[idx] autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:obj withOffset:5];
		[rightViews[idx] autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:5 relation:NSLayoutRelationGreaterThanOrEqual];
		[rightViews[idx] autoAlignAxis:ALAxisHorizontal toSameAxisOfView:obj];
	}];
	[NSLayoutConstraint autoSetPriority:UILayoutPriorityRequired - 1 forConstraints:^{
		[leftViews autoSetViewsDimensionsToSize:CGSizeMake(24, 24)];
	}];
	[CocoaUtils autoVerticalDistributionToSubviews:leftViews spacing:5 shouldSpacingToSuperviewEdge:NO];
	[leftViews.firstObject autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
	[leftViews.lastObject autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:5];
}

#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];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([SchedulePassengerListCell class])]) {
		SchedulePassengerListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SchedulePassengerListCell class])];
		[CocoaUtils fillSeparatorOfCell:cell];
		SoldStock *stock = data.weaklyAssociatedObject;
		cell.userImgView.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome userIconWithSize:24] fillColor:stock.blockStatusColor];
		cell.nameLabel.text = stock.sold_to_name;
        NSMutableAttributedString *cnLabelAttributedString = [[NSMutableAttributedString alloc] initWithString:stock.otherShortDescription attributes:nil];
        if (stock.busOrTourComb) {
            [cnLabelAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
            [cnLabelAttributedString appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome thLargeIconWithSize:cell.cnLabel.font.pointSize] fillColor:[UIColor darkGrayColor]]];
        }
		cell.cnLabel.attributedText = cnLabelAttributedString;
        
		cell.checkinImgView.image = [UIImage imageNamed:stock.vendor_checkin ? @"icon_bus_boarding_yes" : @"icon_bus_boarding_no"];
		[cell.arrowButton setImage:[data.stronglyAssociatedObject boolValue] ? [DrawUtils imageWithFAKIcon:[FAKFontAwesome angleUpIconWithSize:24] fillColor:[UIColor blackColor]] : [DrawUtils imageWithFAKIcon:[FAKFontAwesome angleDownIconWithSize:24] fillColor:[UIColor blackColor]] forState:UIControlStateNormal];
		[cell.arrowButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
		@weakify(self)
		[cell.arrowButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self changeAccordionActive: ![data.stronglyAssociatedObject boolValue] onTableView: tableView atIndexPath: indexPath];
		} forControlEvents: UIControlEventTouchUpInside];
		[self removeDetailsFromView:cell.detailView];
		if ([data.stronglyAssociatedObject boolValue]) {
			[self addDetailsToView:cell.detailView withSoldStock:stock];
		}
		if (tableView.editing) {
			UIView *view = [[UIView alloc] init];
			view.backgroundColor = [UIColor whiteColor];
			cell.selectedBackgroundView = view;
			if ([self.selectedStocks containsObject:stock]) {
				[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
			} else {
				[tableView deselectRowAtIndexPath:indexPath animated:NO];
			}
		}
		return cell;
	}
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

#pragma mark - Table view delegate

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

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

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didDeselectWithData:data];
}

@end
