//
// BusCheckInViewController.m
// Project
//
// Created by ziv on 2017/7/27.
//
//

#import "BusCheckInViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "CheckInActionHandler.h"
#import "Vars.h"

@interface BusCheckInViewController ()
@property (nonatomic, strong) NSMutableArray<SoldStock *> *selectedStocks;
@property (nonatomic, strong) NSMutableArray *cellDataArrays;
@property (nonatomic, assign, readonly) BOOL allowsCheckIn;
@end

@implementation BusCheckInViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	if (self.allowsCheckIn) {
		self.selectedStocks = [NSMutableArray arrayWithArray:self.entry.stocks];

		self.tableView.editing = YES;
		if (YES) {
			UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight] + 15 * 2)];
			UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
			button.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultTableViewRowHeight]);
			button.backgroundColor = [Vars defaultTintColor];
			button.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
			[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
			[button setTitle:@"Check-In" forState:UIControlStateNormal];
			[button addTarget:self action:@selector(performActionForSelfCheckIn) forControlEvents:UIControlEventTouchUpInside];
			[Utility addRoundedBorderToButton:button];
			[footerView addSubview:button];
			self.tableView.tableFooterView = footerView;
		}
	}

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

#pragma mark - Property

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

#pragma mark - Action

- (void)performActionForSelfCheckIn {
	if (![self validateSelfCheckIn]) {
		return;
	}
	[CheckInActionHandler updateStocks:self.selectedStocks toCheckIn:YES blockStatus:self.entry.order.user ? self.entry.order.user.block_status : [Vars appDelegate].loginUser.block_status commit:^(NSString *message) {
		NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
		[notificationCenter postNotificationName:SelfCheckInDidEditingNotification object:nil];
		if (![StringUtils isEmpty:message]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:message dismissalHandler:^{
				[self didSelfCheckIn];
			}];
		} else {
			[self didSelfCheckIn];
		}
	} rollback:^(NSString *message) {
		if (![StringUtils isEmpty:message]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:message];
		}
	}];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *arrays = [NSMutableArray array];
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			if (self.entry.busRouteName) {
				data.text = self.entry.busRouteName;
			} else {
				data.style = UITableViewCellStyleSubtitle;
				data.text = self.entry.product.name;
				data.detailText = IMLocalizedString(@"Product");
				data.detailTextColor = [UIColor lightGrayColor];
				data.allowsTextLineWrapping = YES;
			}
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = self.entry.localizedDepartureDateString;
			data.detailText = IMLocalizedString(@"Departure Date");
			data.detailTextColor = [UIColor lightGrayColor];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.attributedText = [self.entry getOptionAttributedText:@"departure" withFont:[UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle]];
			data.detailText = @"Departure";
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.attributedText = [self.entry getOptionAttributedText:@"arrival" withFont:[UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleSubtitle]];
			data.detailText = @"Arrival";
			data.detailTextColor = [UIColor lightGrayColor];
			data.allowsTextLineWrapping = YES;
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = arrays;
	[self updateTableViewCellDataArrayForPassengerList];
}

- (void)updateTableViewCellDataArrayForPassengerList {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.text = self.entry.shortDescription;
		if (self.allowsCheckIn) {
			data.selectedBackgroundColor = [UIColor whiteColor];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.selectedStocks.count != self.entry.stocks.count) {
					[self.selectedStocks removeAllObjects];
					[self.selectedStocks addObjectsFromArray:self.entry.stocks];
				}
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[data setDidDeselectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (self.selectedStocks.count == self.entry.stocks.count) {
					[self.selectedStocks removeAllObjects];
				}
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, id cell) {
				@strongify(self)
				if (self.selectedStocks.count == self.entry.stocks.count) {
					[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
				} else {
					[tableView deselectRowAtIndexPath:indexPath animated:NO];
				}
			}];
		}
		[array addObject:data];
	}
	for (SoldStock *stock in self.entry.stocks) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.text = stock.sold_to_name;
		[data setDetailTextBlock:^NSString *{
			return stock.otherShortDescription;
		}];
		if (self.allowsCheckIn) {
			data.selectedBackgroundColor = [UIColor whiteColor];
			[data setEditingAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
				return [[UIImageView alloc] initWithImage:[UIImage imageNamed:stock.vendor_checkin ? @"icon_bus_boarding_yes" : @"icon_bus_boarding_no"]];
			}];
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if (![self.selectedStocks containsObject:stock]) {
					[self.selectedStocks addObject:stock];
				}
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[data setDidDeselectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				if ([self.selectedStocks containsObject:stock]) {
					[self.selectedStocks removeObject:stock];
				}
				[tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
			}];
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, id cell) {
				@strongify(self)
				if ([self.selectedStocks containsObject:stock]) {
					[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
				} else {
					[tableView deselectRowAtIndexPath:indexPath animated:NO];
				}
			}];
		} else {
			[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
				return [[UIImageView alloc] initWithImage:[UIImage imageNamed:stock.vendor_checkin ? @"icon_bus_boarding_yes" : @"icon_bus_boarding_no"]];
			}];
		}
		[array addObject:data];
	}
	self.cellDataArrays[1] = [NSArray arrayWithArray:array];
}

- (BOOL)validateSelfCheckIn {
	if (self.selectedStocks.count == 0) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select passenger(s) first"];
		return NO;
	}
	return YES;
}

- (void)didSelfCheckIn {
	if (self.tableView.editing != self.allowsCheckIn) {
		self.tableView.editing = self.allowsCheckIn;
		[self updateTableViewCellDataArrayForPassengerList];
		[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
		self.tableView.tableFooterView = nil;
	}
}

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

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	if (tableView.editing && indexPath.section == 1) {
		return YES;
	}
	return NO;
}

- (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 {
	if (![self tableView:tableView canEditRowAtIndexPath: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 didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (![self tableView:tableView canEditRowAtIndexPath:indexPath]) {
		return;
	}
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didDeselectWithData:data];
}

@end
