//
// TrackBusStatusDetailsViewController.m
// Project
//
// Created by Ziv on 2017/5/16.
//
//

#import "BusStatusDetailViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "Collectors.h"
#import "DrawUtils.h"
#import "RandomUtils.h"
#import "CalendarViewController.h"
#import "TextViewController.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "DZNEmptyDataSetDefault.h"
#import "Utility.h"
#import "BusStatusApi.h"
#import "BusStatusDetailResponseJsonMapper.h"
#import "CustomLeftRightTitleToolbar.h"
#import "BusStatusDetailStopCell.h"
#import "UIViewController+Privilege.h"
#import "BusStatusMapViewController.h"
#import "BusStatusDetailStopView.h"
#import "CheckInScanViewController.h"
#import "ScheduleDetailsViewController.h"
#import "CashTicketViewController.h"
#import "ScanCodeViewController.h"
#ifndef TARGET_OF_Chinatown_Bus
 #import "SchedulePassengerListViewController.h"
#endif
#import "Vars.h"

@interface BusStatusDetailViewController () <UITableViewDataSource, UITableViewDelegate,  DZNEmptyDataSetDefault>
@property (nonatomic, weak) IBOutlet CustomLeftRightTitleToolbar *datePickerToolbar;
@property (nonatomic, weak) IBOutlet UIScrollView *scrollView;
@property (nonatomic, weak) IBOutlet UITableView *tableView;

@property (nonatomic, strong) BusStatusDetailResponse *busStatusDetailResponse;
@property (nonatomic, strong) NSDate *dateObj;

@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) NSArray *sectionHeaderTitles;

@property (nonatomic, strong, readonly) NSDictionary<NSString *, NSArray<BusStatusDetailBean *> *> *datedBusStatusDetails;
@property (nonatomic, strong, readonly) NSArray *sortedDateKeys;
@property (nonatomic, strong) NSArray<BookingReportSummaryBean *> *bookingReportSummaryList;
@property (nonatomic, assign) NSInteger combinationStopIndex;
@end

@implementation BusStatusDetailViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.dateObj = [[DateFormatUtils ISO_DATE_FORMAT] parse:self.departureDate];

	BOOL flag = YES;
	if (self.allowsEditing && self.isScheduleDriver) {
		if ([Vars appDelegate].loginUser.is_bus_driver) {
			flag = NO;
		}
	}
	if (flag) {
		UIBarButtonItem *infoItem = [[UIBarButtonItem alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome infoCircleIconWithSize:24] fillColor:[UIColor whiteColor]] style:UIBarButtonItemStylePlain target:self action:@selector(performSegueForImportantInfo)];
		infoItem.imageInsets = UIEdgeInsetsMake(0, 24, 0, -24);
		UIBarButtonItem *mapItem = [[UIBarButtonItem alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome mapIconWithSize:20] fillColor:[UIColor whiteColor]] style:UIBarButtonItemStylePlain target:self action:@selector(performSegueForMap)];
		mapItem.tag = NSStringFromClass([UIBarButtonItem class]).hash;
		self.navigationItem.rightBarButtonItems = @[mapItem, infoItem];
	} else {
		UIBarButtonItem *infoItem = [[UIBarButtonItem alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome infoCircleIconWithSize:24] fillColor:[UIColor whiteColor]] style:UIBarButtonItemStylePlain target:self action:@selector(performSegueForImportantInfo)];
		self.navigationItem.rightBarButtonItem = infoItem;
	}

	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BusStatusDetailStopCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([BusStatusDetailStopCell class])];
    
	[self buildHeaderFooterView];
}

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

#pragma mark - Network

- (void)getBusStatusDetail {
	BusStatusDetail *busStatusDetail = [[BusStatusDetail alloc] init];
	busStatusDetail.departureDate = [[DateFormatUtils ISO_DATE_FORMAT] format:self.dateObj];
	busStatusDetail.productId = self.product.product_id;
	busStatusDetail.scheduleId = self.schedule.id;
	busStatusDetail.editing = self.allowsEditing;
    busStatusDetail.isDBDSearch = self.isDBDBookingSearch;
	
	NSDictionary *requestDict = [BeanUtils describeAccessible:busStatusDetail];

	UIBarButtonItem *mapItem = [self.navigationItem.rightBarButtonItems bk_match:^BOOL (UIBarButtonItem *obj) {
		return obj.tag == NSStringFromClass([UIBarButtonItem class]).hash;
	}];
	self.tableView.emptyDataSetSource = nil;
	
	[Utility performRESTRequestWithMethod:@"POST" url:busStatusDetail.address parameters:requestDict beforeSend:^{
		mapItem.enabled = NO;
		[CocoaUtils showBusyIndicator:self.view];
	} success:^(id jsonObject) {
//         NSLog(@"%@", jsonObject);
		BusStatusDetailResponseJsonMapper *mapper = [[BusStatusDetailResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]) {
			BusStatusDetailResponse *response = mapper.response;
			// NSLog(@"%@", response);
			self.busStatusDetailResponse = response;
			[self buildSectionHeaderTitle];
			[self buildCellDataSource];
			self.tableView.emptyDataSetSource = self;
			[self.tableView reloadData];
            [self drawScrollView];
			[self reloadFooterView];
		}
	} complete:^{
		[CocoaUtils hideBusyIndicator:self.view];
		mapItem.enabled = YES;
	}];
}

#pragma mark - Property

- (NSArray *)sortedDateKeys {
	return [self.datedBusStatusDetails.allKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}

- (NSDictionary *)datedBusStatusDetails {
	return [Collectors groupingBy:self.busStatusDetailResponse.resultList classifierWithBlock:^id < NSCopying > (BusStatusDetailBean *obj) {
		return [obj.nextDayValue substringToIndex:10];
	}];
}

-(NSInteger)combinationStopIndex{
    if (!self.busStatusDetailResponse) {
        return 0;
    }
    
    for (BusStatusDetailBean *bean in self.busStatusDetailResponse.resultList) {
        if (bean.combinationArrCross) {
            return [self.busStatusDetailResponse.resultList indexOfObject:bean];
        }
    }
    return 0;
}

#pragma mark - Segue

- (void)performSegueForImportantInfo {
	UIFont *contentFont = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
	UIFont *boldContentFont = [CocoaUtils renderedFont:contentFont withSymbolicTraits:UIFontDescriptorTraitBold];
	TextViewController *viewController = [[TextViewController alloc] init];
	viewController.title = @"IMPORTANT INFO";
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	NSMutableAttributedString *text = [[NSMutableAttributedString alloc] init];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"On-time service is based on estimated departure and arrival times, which may be delayed by various factors including weather, traffic and road conditions." attributes:@{NSFontAttributeName : contentFont}]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n\n"]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"(a)" attributes:@{NSFontAttributeName : boldContentFont}]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@" = arrival time " attributes:@{NSFontAttributeName : contentFont}]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"(d)" attributes:@{NSFontAttributeName : boldContentFont}]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@" = departure time" attributes:@{NSFontAttributeName : contentFont}]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n\n"]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"Key: " attributes:@{NSFontAttributeName : boldContentFont}]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"Expected times will be shown in red when a schedule is currently delayed by more than 15 minutes." attributes:@{NSFontAttributeName : contentFont}]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n\n"]];
	[text appendAttributedString:[[NSAttributedString alloc] initWithString:@"* Real-time information is not available for this schedule, as it hasn't started yet, but it is expected to be on time." attributes:@{NSFontAttributeName : contentFont}]];
	viewController.textView.attributedText = text;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForMap {
	BusStatusMapViewController *viewController = [[BusStatusMapViewController alloc] init];
	viewController.busStatusDetailResponse = self.busStatusDetailResponse;
	viewController.departureDate = self.departureDate;
	viewController.product = self.product;
	viewController.schedule = self.schedule;
	viewController.allowsEditing = self.allowsEditing;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForCalendar {
	CalendarViewController *viewController = [[CalendarViewController alloc] init];
	viewController.title = IMLocalizedString(@"Departure Date");
	CalendarManager *manager = viewController.calendarManager;
	[manager setDidSelectDateBlock:^(NSDate *date) {
		[self.navigationController popViewControllerAnimated:YES];
		self.dateObj = date;
		[self getBusStatusDetail];
        self.departureDate = [[DateFormatUtils ISO_DATE_FORMAT] format:self.dateObj];
	}];
	[self.navigationController pushViewController:viewController animated:YES];
}

#ifndef TARGET_OF_Chinatown_Bus

- (void)performSegueForPassengerListWithObject:(BusStatusDetailBean *)bean isPickUp:(BOOL)isPickUp isDropOff:(BOOL)isDropOff {
	SchedulePassengerListViewController *viewController = [[SchedulePassengerListViewController alloc] init];
	viewController.service_date = self.departureDate;
	viewController.scheduleStopId = bean.scheduleStop.id;
    viewController.scheduleId = self.schedule.id;
	viewController.isPickUp = isPickUp;
	viewController.isDropOff = isDropOff;
    viewController.isDBDSearch = self.isDBDBookingSearch;
	if (self.allowsEditing) {
		if ([Vars appDelegate].loginUser.is_vendor) {
            viewController.allowsCheckIn = !self.schedule.route.isCombinationRoute;
		} else if ([Vars appDelegate].loginUser.is_bus_driver && bean.driverAssigned) {
			viewController.allowsCheckIn = YES;
		}
	}
	[self.navigationController pushViewController:viewController animated:YES];
}
#endif

-(void)performSegueForCheckInScanWithObject:(BusStatusDetailBean *)bean{
#ifndef TARGET_OF_Chinatown_Bus
    ScanCodeViewController *viewController = [[ScanCodeViewController alloc] init];
    viewController.scheduleStopId = bean.scheduleStop.id;
    viewController.serviceDate = [[DateFormatUtils ISO_DATE_FORMAT] format: [DateUtils addDays: self.dateObj amount:bean.dateIndex]];
    [self.navigationController pushViewController:viewController animated:YES];
#endif
}

- (void)performSegueForCashTicketBusStatusDetail:(BusStatusDetailBean *)busStatusDetail {
#ifndef TARGET_OF_Chinatown_Bus
    CashTicketViewController *viewController = [[CashTicketViewController alloc] init];
    viewController.service_date =  [[DateFormatUtils ISO_DATE_FORMAT] format: [DateUtils addDays: self.dateObj amount:busStatusDetail.dateIndex]];
    viewController.schedule = self.schedule;
    viewController.stopStationId = busStatusDetail.scheduleStop.id;
    viewController.loadSuccess = ^(NSArray *bookingReportSummary) {
        self.bookingReportSummaryList = bookingReportSummary;
    };
    viewController.bookingReportSummaryList  = self.bookingReportSummaryList;
    viewController.isDBDBookingReport = self.isDBDBookingSearch;
    [self.navigationController pushViewController:viewController animated:YES];
#endif
}

#pragma mark - Private

- (void)buildSectionHeaderTitle {
	NSMutableArray *titleArray = [NSMutableArray array];
	for (NSString *nextDayValue in self.sortedDateKeys) {
		[titleArray addObject:[CocoaUtils localizedStringFromDate:[[DateFormatUtils ISO_DATE_FORMAT] parse:nextDayValue] template:@"EEEMMMd"]];
	}
	self.sectionHeaderTitles = [NSArray arrayWithArray:titleArray];
}

- (void)reloadFooterView {
	UIView *footerView = self.tableView.tableFooterView;
	UILabel *label = [footerView viewWithTag:NSStringFromClass([UILabel class]).hash];
	if (self.busStatusDetailResponse.resultList.count == 0) {
		label.frame = CGRectZero;
		footerView.frame = CGRectZero;
	} else {
		NSDate *starDate = [DateUtils parseDate:[NSString stringWithFormat:@"%@ %@", self.sortedDateKeys.firstObject, self.busStatusDetailResponse.resultList.firstObject.scheduleStop.leavingTime] locale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"] parsePatterns:@"yyyy-MM-dd hh:mm a", nil];
		NSDate *endDate = [DateUtils parseDate:[NSString stringWithFormat:@"%@ %@", self.sortedDateKeys.lastObject, self.busStatusDetailResponse.resultList.lastObject.scheduleStop.arrivalTime] locale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"] parsePatterns:@"yyyy-MM-dd hh:mm a", nil];
		label.text = [NSString stringWithFormat:@"Total duration: %@", [CocoaUtils durationStringWithUnitsStyle:NSDateComponentsFormatterUnitsStyleShort locale:[CocoaUtils applicationLocale] fromDate:starDate toDate:endDate]];
		[label sizeToFit];
		footerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultLabelHeight]);
		label.frame = CGRectSetOrigin(label.frame, CGPointMake(self.tableView.separatorInset.left, (CGRectGetHeight(footerView.frame) - CGRectGetHeight(label.frame)) / 2));
	}
	self.tableView.tableFooterView = footerView;
}

- (void)buildCellDataSource {
    
    BusStatusDetailStopView *view = [BusStatusDetailStopView viewFromNib];
    if (!self.allowsEditing) {
        view.showsToolbar = NO;
        view.showBottomToolbar = NO;
    }
    CGFloat h = [view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height  + [UIConstants defaultTableViewSeparatorHeight] / [UIScreen mainScreen].scale;
    
	NSMutableArray *arrays = [NSMutableArray array];
	for (NSString *nextDayValue in self.sortedDateKeys) {
		NSMutableArray *array = [NSMutableArray array];
		for (BusStatusDetailBean *detail in self.datedBusStatusDetails[nextDayValue]) {

			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([BusStatusDetailStopCell class]);
			data.weaklyAssociatedObject = detail;
            data.reuseHeight = h;
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

- (void)drawBezierPath:(UIBezierPath *)bezierPath addLineWithHeight:(CGFloat)height fromPoint:(CGPoint)point maxY:(CGFloat *)maxY {
	[bezierPath moveToPoint:point];
	[bezierPath addLineToPoint:CGPointMake(point.x, point.y + height)];
	*maxY += height;
}

- (void)drawBezierPath:(UIBezierPath *)bezierPath addArcWithRadius:(CGFloat)radius fromPoint:(CGPoint)point {
	[bezierPath moveToPoint:CGPointMake(point.x + radius, point.y)];
	[bezierPath addArcWithCenter:point radius:radius startAngle:0 endAngle:2 * M_PI clockwise:YES];
}

- (void)drawScrollView {
	self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, self.tableView.contentSize.height);
	CAShapeLayer *shapeLayer1 = [CocoaUtils sublayerWithName:@"shapeLayer1" fromSuperlayer:self.scrollView.layer];
	if (!shapeLayer1) {
		shapeLayer1 = [CAShapeLayer layer];
		shapeLayer1.name = @"shapeLayer1";
		shapeLayer1.strokeColor = [Vars defaultTintColor].CGColor;
		shapeLayer1.fillColor = [Vars defaultTintColor].CGColor;
		shapeLayer1.lineWidth = 2;
		[self.scrollView.layer addSublayer:shapeLayer1];
	}
	CAShapeLayer *shapeLayer2 = [CocoaUtils sublayerWithName:@"shapeLayer2" fromSuperlayer:self.scrollView.layer];
	if (!shapeLayer2) {
		shapeLayer2 = [CAShapeLayer layer];
		shapeLayer2.name = @"shapeLayer2";
		shapeLayer2.strokeColor = [UIColor lightGrayColor].CGColor;
		shapeLayer2.fillColor = [UIColor lightGrayColor].CGColor;
		shapeLayer2.lineWidth = 2;
		[self.scrollView.layer addSublayer:shapeLayer2];
	}
	UIImageView *imageView = [self.scrollView viewWithTag:NSStringFromClass([UIImageView class]).hash];
	if (!imageView) {
		imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_bus_carrier_online"]];;
		imageView.tag = NSStringFromClass([UIImageView class]).hash;
		[self.scrollView addSubview:imageView];
	}
	imageView.hidden = YES;
	UIBezierPath *bezierPath1 = [UIBezierPath bezierPath];
	UIBezierPath *bezierPath2 = [UIBezierPath bezierPath];
	if (self.busStatusDetailResponse.resultList.count > 0 && self.busStatusDetailResponse.resultList.count == [[self.cellDataArrays valueForKeyPath:@"@unionOfArrays.self"] count]) {
		CGFloat sectionHeight = [UIConstants defaultTableViewSectionHeight:UITableViewStylePlain];
        CGFloat rowHeight = CGRectGetHeight([self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]].frame);
		CGFloat centerX = CGRectGetWidth(self.scrollView.frame) / 2;
		CGFloat radius = 2;
		__block CGFloat maxY = 0;
		if (YES) {
			UIBezierPath *bezierPath = nil;
			if (self.busStatusDetailResponse.stopIndex >= 0) {
				bezierPath = bezierPath1;
			} else {
				bezierPath = bezierPath2;
			}
			if (bezierPath) {
				[self drawBezierPath:bezierPath addLineWithHeight:rowHeight / 2 fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
			}
		}
		for (int i = 0; i < self.busStatusDetailResponse.resultList.count - 1; i++) {
			if (i == self.busStatusDetailResponse.stopIndex) {
				[self drawBezierPath:bezierPath1 addArcWithRadius:radius fromPoint:CGPointMake(centerX, maxY)];
				if (self.busStatusDetailResponse.stopProgress < 0.5) {
					[self drawBezierPath:bezierPath1 addLineWithHeight:rowHeight * self.busStatusDetailResponse.stopProgress fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					[self drawBezierPath:bezierPath2 addLineWithHeight:rowHeight * (0.5 - self.busStatusDetailResponse.stopProgress) fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					if (self.busStatusDetailResponse.resultList[i + 1].isShowNextDay) {
						[self drawBezierPath:bezierPath2 addLineWithHeight:sectionHeight fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					}
					[self drawBezierPath:bezierPath2 addLineWithHeight:rowHeight / 2 fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
				} else {
					[self drawBezierPath:bezierPath1 addLineWithHeight:rowHeight / 2 fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					if (self.busStatusDetailResponse.resultList[i + 1].isShowNextDay) {
						[self drawBezierPath:bezierPath1 addLineWithHeight:sectionHeight fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					}
					[self drawBezierPath:bezierPath1 addLineWithHeight:rowHeight * (self.busStatusDetailResponse.stopProgress - 0.5) fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					[self drawBezierPath:bezierPath2 addLineWithHeight:rowHeight * (1.0 - self.busStatusDetailResponse.stopProgress) fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
				}
			} else {
				UIBezierPath *bezierPath = nil;
				if (i < self.busStatusDetailResponse.stopIndex) {
					bezierPath = bezierPath1;
				} else if (i > self.busStatusDetailResponse.stopIndex) {
					bezierPath = bezierPath2;
				}
				if (bezierPath) {
					[self drawBezierPath:bezierPath addArcWithRadius:radius fromPoint:CGPointMake(centerX, maxY)];
					[self drawBezierPath:bezierPath addLineWithHeight:rowHeight / 2 fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					if (self.busStatusDetailResponse.resultList[i + 1].isShowNextDay) {
						[self drawBezierPath:bezierPath addLineWithHeight:sectionHeight fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
					}
					[self drawBezierPath:bezierPath addLineWithHeight:rowHeight / 2 fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
				}
			}
		}
		if (YES) {
			UIBezierPath *bezierPath = nil;
			if (self.busStatusDetailResponse.stopIndex == self.busStatusDetailResponse.resultList.count - 1) {
				bezierPath = bezierPath1;
			} else {
				bezierPath = bezierPath2;
			}
			if (bezierPath) {
				[self drawBezierPath:bezierPath addArcWithRadius:radius fromPoint:CGPointMake(centerX, maxY)];
				[self drawBezierPath:bezierPath addLineWithHeight:rowHeight / 2 fromPoint:CGPointMake(centerX, maxY) maxY:&maxY];
			}
		}
		if (self.busStatusDetailResponse.stopIndex >= 0 && self.busStatusDetailResponse.stopIndex < self.busStatusDetailResponse.resultList.count - 1) {
			imageView.hidden = NO;
			imageView.center = bezierPath1.currentPoint;
		}
	}
	shapeLayer1.path = bezierPath1.CGPath;
	shapeLayer2.path = bezierPath2.CGPath;
}

- (void)buildHeaderFooterView {
	if (YES) {
		@weakify(self)
		[self.datePickerToolbar setLeftBarButtonItemHandler:^{
			@strongify(self)
			[self backwardDate];
		}];
		[self.datePickerToolbar setRightBarButtonItemHandler:^{
			@strongify(self)
			[self forwardDate];
		}];
		[self.datePickerToolbar setTitleBarButtonItemHandler:^{
			@strongify(self)
			[self performSegueForCalendar];
		}];
		if (self.allowsEditing && self.isScheduleDriver) {
			if ([Vars appDelegate].loginUser.is_bus_driver) {
				[self.datePickerToolbar setLeftBarButtonItemHandler:nil];
				[self.datePickerToolbar setRightBarButtonItemHandler:nil];
				[self.datePickerToolbar setTitleBarButtonItemHandler:nil];
				self.datePickerToolbar.leftBarButtonItem.enabled = NO;
				self.datePickerToolbar.titleBarButtonItem.enabled = NO;
				self.datePickerToolbar.rightBarButtonItem.enabled = NO;
			}
		}
		[self checkDateStepButton];
	}
	if (YES) {
		UIView *footerView = [[UIView alloc] init];
		footerView.backgroundColor = [CocoaUtils colorWithRGBs:0xf7f7f7];
		UILabel *label = label = [[UILabel alloc] init];
		label.tag = NSStringFromClass([UILabel class]).hash;
		[footerView addSubview:label];
		label.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
		self.tableView.tableFooterView = footerView;
	}
}

- (void)backwardDate {
	self.dateObj = [DateUtils addDays:self.dateObj amount:-1];
	[self checkDateStepButton];
	[self getBusStatusDetail];
}

- (void)forwardDate {
	self.dateObj = [DateUtils addDays:self.dateObj amount:1];
	[self checkDateStepButton];
	[self getBusStatusDetail];
}

- (void)checkDateStepButton {
	self.datePickerToolbar.titleBarButtonItem.title = [Utility localizedStringWithDate:self.dateObj];
}

- (void)addButtonEventInUItableviewCell:(BusStatusDetailStopCell *)cell withBean:(BusStatusDetailBean *)bean{

    [cell.contentDetailView.scanQRCodeButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
    [cell.contentDetailView.cashTicketButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
    [cell.contentDetailView.driverInfoButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
    
    [cell.contentDetailView.scanQRCodeButton bk_addEventHandler:^(id   sender) {
        [self performSegueForCheckInScanWithObject:bean];
    } forControlEvents:UIControlEventTouchUpInside];

    [cell.contentDetailView.cashTicketButton bk_addEventHandler:^(id   sender) {
        [self performSegueForCashTicketBusStatusDetail:bean];
    } forControlEvents:UIControlEventTouchUpInside];
    
    [cell.contentDetailView.driverInfoButton bk_addEventHandler:^(id   sender) {
        
    } forControlEvents:UIControlEventTouchUpInside];
}

-(NSArray *)filterSchedule{

    NSArray *stopList = [self.busStatusDetailResponse.resultList bk_select:^BOOL(BusStatusDetailBean * busStatusDetail) {
        if ((busStatusDetail.arrivalStopStatus && busStatusDetail.arrivalStopStatus.status != 3)  && (busStatusDetail.combinationArrCross == 0 && busStatusDetail.combinationDepCross == 0)){
                return YES;
            }
        return NO;
    }];
    return stopList;
}

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if (section > 0) {
		return self.sectionHeaderTitles[section];
	}
	return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([BusStatusDetailStopCell class])]) {
		BusStatusDetailStopCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BusStatusDetailStopCell class])];
		BusStatusDetailBean *bean = data.weaklyAssociatedObject;
		cell.backgroundColor = bean.isCancelled ? [UIColor lightGrayColor] : [UIColor whiteColor];
		if (YES) {
			NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:bean.scheduleStop.busstation.destination.show_name attributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]}]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:bean.scheduleStop.busstation.name attributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1]}]];
			cell.contentDetailView.stopNameLabel.attributedText = attributedString;
		}
		cell.contentDetailView.scheduledTimeLabel.attributedText = bean.attributedScheduledTimeText;
		cell.contentDetailView.statusTimeLabel.attributedText = bean.attributedStatusTimeText;
		cell.contentDetailView.showsToolbar = NO;
        cell.contentDetailView.showBottomToolbar = NO;
		cell.contentDetailView.driverInfoButton.hidden = YES;
		if (self.allowsEditing) {
#ifndef TARGET_OF_Chinatown_Bus
			if ([Vars appDelegate].loginUser.is_vendor || [Vars appDelegate].loginUser.is_bus_driver) {
                cell.contentDetailView.isPickUp = bean.scheduleStop.isPickUp;
               cell.contentDetailView.isDropOff = bean.scheduleStop.isDropOff;
				if (bean.scheduleStop.isPickUp) {
					[cell.contentDetailView.pickUpButton setTitle:[NSString stringWithFormat:@"%d", bean.scheduleStop.pickUpPassengerNum] forState:UIControlStateNormal];
					[cell.contentDetailView.checkInButton setTitle:[NSString stringWithFormat:@"%d", bean.scheduleStop.checkInPassengerNum] forState:UIControlStateNormal];
					[cell.contentDetailView.uncheckedButton setTitle:[NSString stringWithFormat:@"%d", bean.scheduleStop.uncheckedPassengerNum] forState:UIControlStateNormal];
				} else {
					[cell.contentDetailView.pickUpButton setTitle:@"N/A" forState:UIControlStateNormal];
					[cell.contentDetailView.checkInButton setTitle:@"N/A" forState:UIControlStateNormal];
					[cell.contentDetailView.uncheckedButton setTitle:@"N/A" forState:UIControlStateNormal];
				}
				if (bean.scheduleStop.isDropOff) {
					[cell.contentDetailView.dropOffButton setTitle:[NSString stringWithFormat:@"%d", bean.scheduleStop.dropOffPassengerNum] forState:UIControlStateNormal];
				} else {
					[cell.contentDetailView.dropOffButton setTitle:@"N/A" forState:UIControlStateNormal];
				}
				[cell.contentDetailView.pickUpButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
				[cell.contentDetailView.checkInButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
				[cell.contentDetailView.uncheckedButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
				[cell.contentDetailView.dropOffButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
				@weakify(self)
				if (bean.scheduleStop.isPickUp && bean.scheduleStop.pickUpPassengerNum > 0) {
					[cell.contentDetailView.pickUpButton bk_addEventHandler:^(id sender) {
						@strongify(self)
						[self performSegueForPassengerListWithObject: bean isPickUp:YES isDropOff: NO];
					} forControlEvents:UIControlEventTouchUpInside];
				}
				if (bean.scheduleStop.isPickUp && bean.scheduleStop.checkInPassengerNum > 0) {
					[cell.contentDetailView.checkInButton bk_addEventHandler:^(id sender) {
						@strongify(self)
						[self performSegueForPassengerListWithObject: bean isPickUp:YES isDropOff: NO];
					} forControlEvents:UIControlEventTouchUpInside];
				}
				if (bean.scheduleStop.isPickUp && bean.scheduleStop.uncheckedPassengerNum > 0) {
					[cell.contentDetailView.uncheckedButton bk_addEventHandler:^(id sender) {
						@strongify(self)
						[self performSegueForPassengerListWithObject: bean isPickUp:YES isDropOff: NO];
					} forControlEvents:UIControlEventTouchUpInside];
				}
				if (bean.scheduleStop.isDropOff && bean.scheduleStop.dropOffPassengerNum > 0) {
					[cell.contentDetailView.dropOffButton bk_addEventHandler:^(id sender) {
						@strongify(self)
						[self performSegueForPassengerListWithObject: bean isPickUp:NO isDropOff: YES];
					} forControlEvents:UIControlEventTouchUpInside];
				}
                [self addButtonEventInUItableviewCell:cell withBean:bean];
                
                cell.contentDetailView.showsToolbar = YES;
                cell.contentDetailView.showBottomToolbar = YES;
                
                if (bean.combinationArrCross || bean.combinationDepCross) {
                    cell.contentDetailView.showBottomToolbar = NO;
                    cell.contentDetailView.showsToolbar = NO;
                } else {
                    if (!bean.scheduleStop.isPickUp) {
                        cell.contentDetailView.showBottomToolbar = NO;
                    }
                    if (self.schedule.route.isCombinationRoute) {
                         cell.contentDetailView.scanQRCodeButton.hidden = YES;
                        if (indexPath.row >= self.combinationStopIndex) {
                            cell.contentDetailView.showBottomToolbar =  NO;
                        }
                    }
                    if ([Vars appDelegate].loginUser.is_bus_driver && !bean.driverAssigned) {
                        cell.contentDetailView.showBottomToolbar = NO;
                    }
                    if ([Vars appDelegate].loginUser.is_bus_driver) {
                        cell.contentDetailView.cashTicketButton.hidden = YES;
                    }
                }
			}
			if ([Vars appDelegate].loginUser.is_vendor) {
				[cell.contentDetailView.driverInfoButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
				if (bean.assignedDrivers.count > 0) {
					cell.contentDetailView.driverInfoButton.hidden = NO;
					[cell.contentDetailView.driverInfoButton bk_addEventHandler:^(id sender) {
						UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Driver Info" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
						for (DriverBean *driver in bean.assignedDrivers) {
							BOOL isValidPhoneNumber = ![StringUtils isEmpty:driver.phone] && [Utility isValidPhoneNumber:driver.phone];
							if (isValidPhoneNumber) {
								UIAlertAction *callAction = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"Call %@",driver.name] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
									[Utility callPhoneNumber:driver.phone];
								}];
								[callAction setValue:[[UIImage imageNamed:@"phone"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"_image"];
								[alertController addAction:callAction];
							}
						}
						UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"Cancle" style:UIAlertActionStyleCancel handler:nil];
						[alertController addAction:cancleAction];
						[self presentViewController:alertController animated:YES completion:nil];
					} forControlEvents:UIControlEventTouchUpInside];
				}
			}
#endif
		}
		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.cellDataArrays[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData: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];
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
	UITableViewHeaderFooterView *footerView = (UITableViewHeaderFooterView *)view;
	footerView.textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
}

#pragma mark - Scroll view delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	self.scrollView.contentOffset = scrollView.contentOffset;
	self.tableView.contentOffset = scrollView.contentOffset;
}

@end
