//
// SalesEntryListViewController.m
// MyProject
//
// Created by haibara on 15/6/15.
//
//

#import "PurchaseRecordViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "NavigationItemSheet.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "DZNEmptyDataSetDefault.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 "PerlWS.h"
#import "UIViewController+Privilege.h"
#import "PurchaseRecordResponseJsonMapper.h"
#import "PurchaseRecordItineraryCell.h"
#import "SalesEntryDetailViewController.h"
#import "Vars.h"
#import "LoginViewController.h"
#ifndef TARGET_OF_TakeTours
#import "BusCheckInViewController.h"
#import "BusStatusDetailViewController.h"
#endif

@interface PurchaseRecordViewController () <DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,purchaseRecordItineraryDelegate>

@property (nonatomic, assign) BOOL isUpcoming;
@property (nonatomic, assign) NSInteger selectedValue;
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) UIButton *refreshButton;

@property (nonatomic, strong, readonly) NSArray *dateRangeValues;
@property (nonatomic, strong, readonly) NSArray *dateRangeTexts;
@end

@implementation PurchaseRecordViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(didChangeLoginStatus) name:LoginStatusDidChangeNotification object:nil];
    
    self.isUpcoming = YES;
    self.selectedValue = [self.dateRangeValues.firstObject intValue];
	UIButton * refreshButton = [[UIButton alloc] init];
	[refreshButton setImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome refreshIconWithSize:24] fillColor:[Vars is_bus_site] ? [UIColor whiteColor] : [Vars defaultTintColor]] forState:UIControlStateNormal];
	[refreshButton addTarget:self action:@selector(reloadOrders) forControlEvents:UIControlEventTouchUpInside];
	self.refreshButton = refreshButton;
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refreshButton];

	if (![Vars appDelegate].loginUser) {
		self.refreshButton.hidden = YES;
	}
	
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.sectionHeaderHeight = [UIConstants defaultTableViewCellLayoutInsets].top;
    self.tableView.sectionFooterHeight = [UIConstants defaultTableViewCellLayoutInsets].bottom;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PurchaseRecordItineraryCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([PurchaseRecordItineraryCell class])];
    
    if (YES) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultSegmentedControlHeight] + 15 * 2)];
        UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:@[[Vars is_cn_website] ? IMLocalizedString(@"Upcoming Orders") : @"Upcoming", [Vars is_cn_website] ? IMLocalizedString(@"Past Orders") : @"Past"]];
        segmentedControl.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultSegmentedControlHeight]);
        segmentedControl.selectedSegmentIndex = 0;
        [segmentedControl addTarget:self action:@selector(changedRT:) forControlEvents:UIControlEventValueChanged];
        [headerView addSubview:segmentedControl];
        self.tableView.tableHeaderView = headerView;
    }
    
    [self buildCellDataSource];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // ajax
    [self fetchOrReloadOrders];
    
}

#pragma mark - Property

- (NSArray *)dateRangeValues {
    return @[@14, @30, @90, @180, @360];
}

- (NSArray *)dateRangeTexts {
    return [self.dateRangeValues bk_map:^NSString * (NSNumber *number) {
        return [NSString stringWithFormat:IMLocalizedString(@"Last %d days"), number.intValue];
    }];
}

#pragma mark - Notification

- (void)didChangeLoginStatus {
    if ([Vars appDelegate].loginUser) {
        self.tableView.emptyDataSetSource = self;
        self.tableView.tableHeaderView.hidden = NO;
		self.refreshButton.hidden = NO;
	}else{
		self.refreshButton.hidden = YES;
	}
    
    [self buildCellDataSource];
    [self.tableView reloadData];
}

#pragma mark - Action

- (BOOL)allowsCheckIn:(SalesEntry *)entry {
    return [entry.stocks bk_any:^BOOL (SoldStock *obj) {
        return !obj.vendor_checkin;
    }];
}

- (void)changedRT:(UISegmentedControl *)segmentedControl {
    if (segmentedControl.selectedSegmentIndex == 0) {
        self.isUpcoming = YES;
    } else if (segmentedControl.selectedSegmentIndex == 1) {
        self.isUpcoming = NO;
    }
    
    NSArray *orders = self.isUpcoming ? self.upcomingOrderList : self.pastOrderList;
    if (orders) {
        [self buildCellDataSource];
        [self.tableView reloadData];
    } else {
        [self fetchOrReloadOrders];
    }
}

- (void)pickDateRange {
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    [pickerView.bk_dynamicDataSource implementMethod:@selector(numberOfComponentsInPickerView:) withBlock:^NSInteger (UIPickerView *pickerView) {
        return 1;
    }];
    [pickerView.bk_dynamicDataSource implementMethod:@selector(pickerView:numberOfRowsInComponent:) withBlock:^NSInteger (UIPickerView *pickerView, NSInteger component) {
        return self.dateRangeValues.count;
    }];
    pickerView.dataSource = pickerView.bk_dynamicDataSource;
    [pickerView.bk_dynamicDelegate implementMethod:@selector(pickerView:titleForRow:forComponent:) withBlock:^NSString *(UIPickerView *pickerView, NSInteger row, NSInteger component) {
        return self.dateRangeTexts[row];
    }];
    pickerView.delegate = pickerView.bk_dynamicDelegate;
    if (self.selectedValue > 0) {
        [pickerView selectRow:[self.dateRangeValues indexOfObject:@(self.selectedValue)] inComponent:0 animated:YES];
    }
    NavigationItemSheet *sheet = [[NavigationItemSheet alloc] initWithViews:@[pickerView] handler:^{
        self.selectedValue = [self.dateRangeValues[[pickerView selectedRowInComponent:0]] intValue];
        [self fetchPostOrders];
    }];
    [sheet show];
}

- (void)showDetailWithSalesEntry:(SalesEntry *)entry {
    SalesEntryDetailViewController *viewController = [[SalesEntryDetailViewController alloc] init];
    viewController.entry = entry;
    viewController.allowsShowMap = YES;
    viewController.allowsShowBarcode = YES;
    viewController.allowsSelfCheckIn = YES;
    viewController.allowsSelfReschedule = YES;
    [self.navigationController pushViewController:viewController animated:YES];
}


#pragma mark - Segue
- (void)performSegueForLoginViewController {
    LoginViewController *loginViewController = [[LoginViewController alloc] init
                                                ];
    [self.navigationController pushViewController:loginViewController animated:YES];
}

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

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

#pragma mark - Network

- (void)fetchUpcomingOrders {
    PurchaseReport *report = [[PurchaseReport alloc] init];
    report.start_date = [[DateFormatUtils ISO_DATE_FORMAT] format:[NSDate date]];
    report.date_type = 1;
    
    NSDictionary *requestDict = [Utility perlParamXml:[report innerXML] action:report.name];
    // NSLog(@"%@", requestDict);
    self.tableView.emptyDataSetSource = nil;
    [Utility getXMLFromRequestWithMethod:@"GET" url:report.address parameters:requestDict success:^(NSString *xml) {
        NSString *responseStr = xml;
        // NSLog(@"%@", responseStr);
        PurchaseRecordResponseJsonMapper *mapper = [[PurchaseRecordResponseJsonMapper alloc] init];
        NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
        if (![mapper parseWithJSONObject:jsonDict]) {
            PurchaseRecordResponse *response = mapper.response;
            if (![StringUtils isEmpty:response.error]) {
                [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error];
            } else {
                self.upcomingOrderList = [response.orders sortedArrayUsingComparator:^NSComparisonResult (Sales *obj1, Sales *obj2) {
                    return [[obj1.entries valueForKeyPath:@"@min.service_date"] compare:[obj2.entries valueForKeyPath:@"@min.service_date"]];
                }];
                if (!self.upcomingOrderList) {
                    self.upcomingOrderList = @[];
                }
                [self buildCellDataSource];
                self.tableView.emptyDataSetSource = self;
                [self.tableView reloadData];
                NSInteger upcoming_itineraries_count = [[Sales toEntries:self.upcomingOrderList] bk_select:^BOOL (SalesEntry *obj) {
                    return !obj.cancelled;
                }].count;
                if ([Vars appDelegate].loginUser.upcoming_itineraries_count != upcoming_itineraries_count) {
                    [Vars appDelegate].loginUser.upcoming_itineraries_count = upcoming_itineraries_count;
                    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
                    [notificationCenter postNotificationName:UpcomingItinerariesCountDidChangeNotification object:nil];
                }
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [Utility saveCalendarEventsForUpcomingItinerariesWithOrders:self.upcomingOrderList];
                });
            }
        }
    }];
}

- (void)fetchPostOrders {
    PurchaseReport *report = [[PurchaseReport alloc] init];
    report.start_date = [[DateFormatUtils ISO_DATE_FORMAT] format:[DateUtils addDays:[NSDate date] amount:-1 * self.selectedValue]];
    report.end_date = [[DateFormatUtils ISO_DATE_FORMAT] format:[DateUtils addDays:[NSDate date] amount:-1]];
    report.date_type = 1;
    
    NSDictionary *requestDict = [Utility perlParamXml:[report innerXML] action:@"purchase_report"];
    // NSLog(@"%@", requestDict);
    self.tableView.emptyDataSetSource = nil;
    [Utility getXMLFromRequestWithMethod:@"GET" url:report.address parameters:requestDict success:^(NSString *xml) {
        NSString *responseStr = xml;
        // NSLog(@"%@", responseStr);
        PurchaseRecordResponseJsonMapper *mapper = [[PurchaseRecordResponseJsonMapper alloc] init];
        NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
        if (![mapper parseWithJSONObject:jsonDict]) {
            PurchaseRecordResponse *response = mapper.response;
            if (![StringUtils isEmpty:response.error]) {
                [CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error];
            } else {
                self.pastOrderList = response.orders;
                if (!self.pastOrderList) {
                    self.pastOrderList = @[];
                }
                [self buildCellDataSource];
                self.tableView.emptyDataSetSource = self;
                [self.tableView reloadData];
            }
        }
    }];
}

#pragma mark - Private

- (void)fetchOrReloadOrders {
    if ([Vars appDelegate].loginUser) {
        if (self.isUpcoming) {
            if (!self.upcomingOrderList) {
                [self fetchUpcomingOrders];
            }
        } else {
            if (!self.pastOrderList) {
                [self fetchPostOrders];
            }
        }
    } else {
        self.tableView.tableHeaderView.hidden = YES;
        self.tableView.emptyDataSetSource = self;
        [self.tableView reloadData];
    }
}

- (void)reloadOrders {
    if ([Vars appDelegate].loginUser) {
        if (self.isUpcoming) {
            [self fetchUpcomingOrders];
        } else {
            [self fetchPostOrders];
        }
    }
    
}

- (void)buildCellDataSource {
    
    NSMutableArray *arrays = [NSMutableArray array];
    @weakify(self)
    if (!self.isUpcoming) {
        TableViewCellData *data = [[TableViewCellData alloc] init];
        data.text = self.dateRangeTexts[[self.dateRangeValues indexOfObject:@(self.selectedValue)]];
        data.textColor = [Vars defaultTintColor];
        data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorDown;
        data.accessoryDisclosureIndicatorColor = [Vars defaultTintColor];
        [data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
            @strongify(self)
            [self pickDateRange];
        }];
        [arrays addObject:@[data]];
    }
    NSArray *orders = self.isUpcoming ? self.upcomingOrderList : self.pastOrderList;
    for (Sales *order in orders) {
        NSMutableArray *array = [NSMutableArray array];
        if (YES) {
            TableViewCellData *data = [[TableViewCellData alloc] init];
            data.style = UITableViewCellStyleValue1;
            if (YES) {
                NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] init];
                [attriString appendAttributedString:[[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"Order ID") attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
                [attriString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
                [attriString appendAttributedString:[[NSAttributedString alloc] im_initWithString:order.order_code]];
                [attriString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
                [attriString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[Vars is_cn_website] ? IMLocalizedString(@"Purchase Date") : @"Purchase" attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
                [attriString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
                [attriString appendAttributedString:[[NSAttributedString alloc] im_initWithString:order.localizedPurchaseDateString]];
                data.attributedText = [[NSAttributedString alloc] initWithAttributedString:attriString];
            }
            data.detailText = [@"$" stringByAppendingFormat:@"%g", [[order.entries valueForKeyPath:@"@sum.sold_amount"] floatValue]];
            data.textFont = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption2];
            data.detailTextColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
            data.detailTextFont = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1];
            data.allowsTextLineWrapping = YES;
            [array addObject:data];
        }
        for (SalesEntry *entry in order.entries) {
            TableViewCellData *data = [[TableViewCellData alloc] init];
            data.reuseIdentifier = NSStringFromClass([PurchaseRecordItineraryCell class]);
            data.weaklyAssociatedObject = entry;
            [data setNeedLayoutFittingHeight];
            [data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
                @strongify(self)
                [self showDetailWithSalesEntry: entry];
            }];
            
            [array addObject:data];
        }
        [arrays addObject:[NSArray arrayWithArray:array]];
    }
    self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return self.cellDataArrays.count;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    if ([data.reuseIdentifier isEqualToString:NSStringFromClass([PurchaseRecordItineraryCell class])]) {
        PurchaseRecordItineraryCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PurchaseRecordItineraryCell class])];
        cell.delegate = self;
        SalesEntry *entry = data.weaklyAssociatedObject;
        cell.trackBusButton.hidden = YES;
        cell.checkinButton.hidden = YES;
		cell.bottomView.hidden = YES;
        if (!entry.cancelled && [entry.product is_bus]) {
            cell.checkinButton.hidden = NO;
			cell.bottomView.hidden = NO;
        }
        if (entry.bus_status_info.status > 0 && [entry.product is_bus]) {
            cell.trackBusButton.hidden = NO;
			cell.bottomView.hidden = NO;
        }
		if (cell.bottomView.hidden) {
			[cell.bottomView removeFromSuperview];
		}
        if (YES) {
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
            [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"Itinerary ID") attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
            [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
            [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:entry.itinerary_id attributes:@{ NSForegroundColorAttributeName : entry.cancelled ? [UIColor darkGrayColor] : [UIColor darkTextColor] }]];
            cell.itineraryLabel.attributedText = [[NSAttributedString alloc] initWithAttributedString:attributedString];
        }
        cell.statueLabel.text = entry.status_name;
        if (entry.busRouteName) {
            cell.productLabel.text = IMLocalizedString(@"Schedule");
            cell.productContentLabel.text = entry.busRouteName;
        } else {
            cell.productLabel.text = IMLocalizedString(@"Product");
            cell.productContentLabel.text = entry.product.name;
        }
        if (YES) {
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
            [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[Vars is_cn_website] ? IMLocalizedString(@"Departure Date") : @"Departure" attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
            [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
            [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:entry.localizedDepartureDateString attributes:@{ NSForegroundColorAttributeName : entry.cancelled ? [UIColor darkGrayColor] : [UIColor darkTextColor] }]];
            if (entry.bus_status_info.status > 0) {
                [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
                [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"Bus Status") attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }]];
                [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
                [attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:entry.bus_status_info.statusName attributes:@{ NSForegroundColorAttributeName : entry.cancelled ? [UIColor darkGrayColor] : entry.bus_status_info.statusColor }]];
            }
            cell.depatureLabel.attributedText = [[NSAttributedString alloc] initWithAttributedString:attributedString];
        }
        cell.priceLabel.text = [@"$" stringByAppendingFormat:@"%g", entry.sold_amount];
        if (entry.cancelled) {
            cell.productContentLabel.textColor = [UIColor darkGrayColor];
            cell.statueLabel.textColor = [UIColor darkGrayColor];
            cell.priceLabel.textColor = [UIColor darkGrayColor];
            [cell.accessoryImageView setBackgroundColor:[UIColor clearColor]];
            cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
        } else {
            cell.productContentLabel.textColor = [UIColor darkTextColor];
            cell.statueLabel.textColor = [CocoaUtils colorWithRGBs:StandardColorBlue];
            cell.priceLabel.textColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
            cell.accessoryImageView = [DrawUtils tableViewCellAccessoryDisclosureIndicatorRightWithColor:[Vars defaultTintColor]];
            cell.backgroundColor = [UIColor whiteColor];
        }
        cell.priceLabel.hidden = entry.order.entries.count == 1;
		[cell updateConstraintsIfNeeded];
        return cell;
    }
    return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    if ([data.reuseIdentifier isEqualToString:NSStringFromClass([PurchaseRecordItineraryCell class])]) {
        return [UIToolkit instantiateRowHeightForTableViewCellWithNibName:NSStringFromClass([PurchaseRecordItineraryCell 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];
}

- (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 - <DZNEmptyDataSetSource>
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    if (![Vars appDelegate].loginUser) {
        return [[NSAttributedString alloc] initWithString:@"Welcome Back!" attributes:@{  NSForegroundColorAttributeName : [UIColor darkGrayColor] }];
    }
    return [[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"No Results") attributes:@{ NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody], NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    if (![Vars appDelegate].loginUser) {
        return [[NSAttributedString alloc] initWithString:@"Login and manage your bookings easily" attributes:nil];
    }
    return nil;
    ;
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    if (![Vars appDelegate].loginUser) {
		return [[NSAttributedString alloc] initWithString:@"Log in" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]}];
    }
    return nil;
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    if (![Vars appDelegate].loginUser) {
        [self performSegueForLoginViewController];
    }
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    if ([Vars appDelegate].loginUser) {
        return [DrawUtils imageWithFAKIcon:[FAKFontAwesome fileOIconWithSize:100] fillColor:[UIColor mercuryColor]];
    } else {
        return [DrawUtils imageWithFAKIcon:[FAKFontAwesome suitcaseIconWithSize:48] fillColor:[UIColor darkGrayColor]];
    }
    return nil;
}

- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor whiteColor];
}

- (void)emptyDataSetDidAppear:(UIScrollView *)scrollView {
	if (![Vars appDelegate].loginUser) {
		UIButton *LoginButton = [[scrollView valueForKey:@"emptyDataSetView"] valueForKey:@"button"];
		[LoginButton setTitle:@"Log in" forState:UIControlStateNormal];
		[LoginButton setBackgroundColor:[Vars defaultTintColor]];
		[Utility addRoundedBorderToView:LoginButton];
		CGRect buttonFrame = LoginButton.frame;
		buttonFrame.size.width -= 80;
		buttonFrame.size.height = 40;
		buttonFrame.origin.x += 40;
		LoginButton.frame = buttonFrame;
	}
}


#pragma mark - purchaseRecordItineraryDelegate
- (void)checkInWithCell:(UITableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    SalesEntry *entry = data.weaklyAssociatedObject;
    [self performSegueForSelfCheckIn:entry];
}


- (void)trackBusWithCell:(UITableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
    SalesEntry *entry = data.weaklyAssociatedObject;
    [self performSegueForBusStatusDetails:entry];
}
@end
