//
// ScheduleDriverSearchViewController.m
// Project
//
// Created by ziv on 2017/5/27.
//
//

#import "ScheduleDriverSearchViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "CalendarViewController.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "DZNEmptyDataSetDefault.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "Route.h"
#import "Schedule.h"
#import "BusStatusApi.h"
#import "BookingReportScheduleListResponseJsonMapper.h"
#import "CustomLeftRightTitleToolbar.h"
#import "BusStatusDetailViewController.h"
#import "ScheduleDriverLocationViewController.h"
#import "Vars.h"

@interface ScheduleDriverSearchViewController () <DZNEmptyDataSetDefault>
@property (nonatomic, strong) NSDate *dateObj;
@property (nonatomic, strong) CustomLeftRightTitleToolbar *datePickerToolbar;
@property (nonatomic, strong) NSArray *routeList;
@property (nonatomic, strong) NSArray *cellDataArray;
@property (nonatomic, strong) Schedule *selectedSchedule;
@end

@implementation ScheduleDriverSearchViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.dateObj = [NSDate date];

	if (YES) {
		@weakify(self)
		self.datePickerToolbar = [[CustomLeftRightTitleToolbar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight])];
		[self.datePickerToolbar setLeftBarButtonItemHandler:^{
			@strongify(self)
			[self backwardDate];
		}];
		[self.datePickerToolbar setRightBarButtonItemHandler:^{
			@strongify(self)
			[self forwardDate];
		}];
		[self.datePickerToolbar setTitleBarButtonItemHandler:^{
			@strongify(self)
			[self performSegueForCalendar];
		}];
		[self checkDateStepButton];
		self.tableView.tableHeaderView = self.datePickerToolbar;
	}
	if (YES) {
		@weakify(self)
		UIView *footerView = [[UIView alloc] init];

		UIButton *checkInButton = [UIButton buttonWithType:UIButtonTypeSystem];
		checkInButton.tag = NSStringFromClass([UIButton class]).hash + 0;
		checkInButton.backgroundColor = [Vars defaultTintColor];
		[checkInButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[checkInButton setTitle:@"Check-In" forState:UIControlStateNormal];
		[checkInButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self performSegueForMap];
		} forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:checkInButton];
		[footerView addSubview:checkInButton];

		UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeSystem];
		detailButton.tag = NSStringFromClass([UIButton class]).hash + 1;
		detailButton.backgroundColor = [UIColor whiteColor];
		[detailButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
		[detailButton setTitle:@"View Details" forState:UIControlStateNormal];
		[detailButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self performSegueForDetails];
		} forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToView:detailButton];
		[footerView addSubview:detailButton];

		self.tableView.tableFooterView = footerView;
	}
	self.tableView.emptyDataSetSource = self;
}

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

#pragma mark - Network

- (void)getDriverAssignInfo {
	self.selectedSchedule = nil;

	ScheduleDriverAssignInfo *scheduleDriverAssignInfo = [[ScheduleDriverAssignInfo alloc] init];
	scheduleDriverAssignInfo.departureDate = [[DateFormatUtils ISO_DATE_FORMAT] format:self.dateObj];

	NSDictionary *requestDict = [BeanUtils describeAccessible:scheduleDriverAssignInfo];
	self.tableView.emptyDataSetSource = nil;
	[Utility performRESTRequestWithMethod:@"POST" url:scheduleDriverAssignInfo.address parameters:requestDict success:^(id jsonObject) {
		BookingReportScheduleListResponseJsonMapper *mapper = [[BookingReportScheduleListResponseJsonMapper alloc] init];
		if (![mapper parseWithJSONObject:jsonObject]) {
			BookingReportResponse *response = mapper.response;
			if (response.errorCode > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.errorMessage];
			} else {
				self.routeList = response.routeList;
				[self buildCellDataSource];
				self.tableView.emptyDataSetSource = self;
				[self.tableView reloadData];
				[self reloadFooterView];
			}
		}
	}];
}

#pragma mark - Segue

- (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 checkDateStepButton];
		self.routeList = nil;
	}];
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForMap {
	if (self.routeList.count == 0) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"No schedules were found that assigned to you"];
		return;
	}
	if (!self.selectedSchedule) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select schedule first"];
		return;
	}
	ScheduleDriverLocationViewController *viewController = [[ScheduleDriverLocationViewController alloc] init];
	viewController.departureDate = [[DateFormatUtils ISO_DATE_FORMAT] format:self.dateObj];
	viewController.schedule = self.selectedSchedule;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForDetails {
	if (self.routeList.count == 0) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"No schedules were found that assigned to you"];
		return;
	}
	if (!self.selectedSchedule) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select schedule first"];
		return;
	}
	BusStatusDetailViewController *viewController = [[BusStatusDetailViewController alloc] init];
	viewController.departureDate = [[DateFormatUtils ISO_DATE_FORMAT] format:self.dateObj];
	viewController.schedule = self.selectedSchedule;
	viewController.allowsEditing = YES;

	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	for (Route *route in self.routeList) {
		for (Schedule *schedule in route.schedules) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = route.shortName;
			NSDate *time = [DateUtils parseDate:schedule.leavingTime parsePatterns:@"HH:mm", nil];
			data.detailText = [CocoaUtils localizedStringFromDate:time template:@"hmma"];
			[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
				@strongify(self)
				if (schedule == self.selectedSchedule) {
					return [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKIonIcons iosCheckmarkOutlineIconWithSize:24] fillColor:[Vars defaultTintColor]]];
				} else {
					return [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:[FAKIonIcons iosCircleOutlineIconWithSize:24] fillColor:[Vars defaultTintColor]]];
				}
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				self.selectedSchedule = schedule;
				[self.tableView reloadData];
			}];
			[array addObject:data];
		}
	}
	self.cellDataArray = array;
}

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

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

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

- (void)reloadFooterView {
	UIView *footerView = self.tableView.tableFooterView;
	UIButton *checkInButton = [footerView viewWithTag:NSStringFromClass([UIButton class]).hash + 0];
	UIButton *detailButton = [footerView viewWithTag:NSStringFromClass([UIButton class]).hash + 1];
	if (self.routeList.count == 0) {
		checkInButton.frame = CGRectZero;
		detailButton.frame = CGRectZero;
		footerView.frame = CGRectZero;
	} else {
		NSInteger dayInterval = [CocoaUtils dateIntervalForComponent:NSCalendarUnitDay fromDate:[DateUtils truncate:[NSDate date] unit:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay] toDate:self.dateObj];
		checkInButton.frame = (dayInterval >= -2 && dayInterval <= 0) ? CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]) : CGRectZero;
		detailButton.frame = CGRectMake(15, CGRectGetMaxY(checkInButton.frame) + 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]);
		footerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetMaxY(detailButton.frame) + 15);
	}
	self.tableView.tableFooterView = footerView;
}

#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];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

#pragma mark - Table view delegate

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

@end
