//
// ScheduleSummaryListViewController.m
// Project
//
// Created by Ziv on 17/3/27.
//
//

#import "BookingReportScheduleListViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "BeanUtils.h"
#import "CocoaUtils.h"
#import "DrawUtils.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 "RouteAPI.h"
#import "BookingReportScheduleListResponseJsonMapper.h"
#import "BusStatusDetailViewController.h"
#import "ScheduleDetailsViewController.h"
#import "Vars.h"

@interface BookingReportScheduleListViewController () <DZNEmptyDataSetDefault>
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) NSArray *routeList;
@end

@implementation BookingReportScheduleListViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.title = self.service_date;

	self.tableView.sectionHeaderHeight = [UIConstants defaultTableViewCellLayoutInsets].top;
	self.tableView.sectionFooterHeight = [UIConstants defaultTableViewCellLayoutInsets].bottom;
	self.tableView.emptyDataSetSource = self;
}

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

#pragma mark - Network

- (void)getBusScheduleList {
	BookingReport *bookingReport = [[BookingReport alloc] init];
	bookingReport.departureDate = self.service_date;
    bookingReport.isDBDBookingReport = self.isDBDBookingReport;
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:bookingReport];
	self.tableView.emptyDataSetSource = nil;
	[Utility performRESTRequestWithMethod:@"POST" url:bookingReport.address parameters:requestDict success:^(id jsonObject) {
		// NSLog(@"%@", 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];
			}
		}
	}];
}

#pragma mark - Segue

- (void)performSegueForBusStatusDetailWithSchedule:(Schedule *)schedule{
	BusStatusDetailViewController *viewController = [[BusStatusDetailViewController alloc] init];
	viewController.departureDate = self.service_date;
	viewController.schedule = schedule;
	viewController.allowsEditing = YES;
    viewController.isDBDBookingSearch = self.isDBDBookingReport;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForCashTicketWithSchedule:(Schedule *)schedule {
	ScheduleDetailsViewController *viewController = [[ScheduleDetailsViewController alloc] init];
	viewController.service_date = self.service_date;
	viewController.schedule = schedule;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *arrays = [NSMutableArray array];
	for (Route *route in self.routeList) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.backgroundColor = route.status == 0 ? [UIColor mercuryColor] : [UIColor whiteColor];
			data.text = route.name;
			if (route.type == 1) {
				data.image = [UIImage imageNamed:@"main"];
			}else if (route.type == 2){
				data.image =   [UIImage imageNamed:@"combination"];
			}else if (route.type == 3){
				data.image = [UIImage imageNamed:@"branch"];
			}
			[data setPreInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath,TableViewCellData *data) {
				if ([data.stronglyAssociatedObject boolValue]) {
					data.textLineNumber = 0;
					data.textLineBreakMode = NSLineBreakByWordWrapping;
				} else {
					data.textLineNumber = 1;
					data.textLineBreakMode = NSLineBreakByTruncatingMiddle;
				}
			}];
			[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				FAKIcon *icon = [data.stronglyAssociatedObject boolValue] ? [FAKFontAwesome angleUpIconWithSize:24] : [FAKFontAwesome angleDownIconWithSize:24];
				return [[UIImageView alloc] initWithImage:[DrawUtils imageWithFAKIcon:icon fillColor:[UIConstants defaultTableViewCellAccessoryDisclosureIndicatorColor]]];
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				data.stronglyAssociatedObject = @(![data.stronglyAssociatedObject boolValue]);
				[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[array addObject:data];
		}
		for (Schedule *schedule in route.schedules) {
			if (schedule.status != -1) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
                data.style = UITableViewCellStyleValue1;
				data.backgroundColor = schedule.status == 0 ? [UIColor mercuryColor] : [UIColor whiteColor];
				if ([StringUtils isEmpty:schedule.leavingTime]) {
					NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
					[attributedString appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome clockOIconWithSize:[UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleDefault].pointSize] fillColor:[UIColor blackColor]]];
					[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
					[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"N/A"]];
					data.attributedText = [[NSAttributedString alloc] initWithAttributedString:attributedString];
				} else {
					NSDate *time = [DateUtils parseDate:schedule.leavingTime parsePatterns:@"HH:mm", nil];
					data.text = [CocoaUtils localizedStringFromDate:time template:@"hmma"];
				}
                data.detailText = [NSString stringWithFormat:@"%d",schedule.scheduleTotalTickets];
                data.detailTextColor = [UIColor darkGrayColor];
				if (schedule.status != 0) {
                    @weakify(self)
                    data.accessoryType = UITableViewCellAccessoryDisclosureIndicatorRight;
					[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
                        @strongify(self)
                        [self performSegueForBusStatusDetailWithSchedule: schedule];
					}];
				}
				[array addObject:data];
			}
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	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];
}

@end
