#import "ProductPickViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "DZNEmptyDataSetDefault.h"
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "Destination.h"
#import "PerlWS.h"
#import "BookingReportProductListCell.h"
#import "BookingSummaryResponseJsonMapper.h"
#import "BookingReportProductFilterViewController.h"
#import "VendorReportController.h"
#import "Vars.h"

@interface ProductPickViewController () <DZNEmptyDataSetDefault>

@property (nonatomic, weak) IBOutlet UITableView *tableView;
@property (nonatomic, weak) IBOutlet UIButton *departureButton;
@property (nonatomic, weak) IBOutlet UIButton *arrivalButton;
@property (nonatomic, weak) IBOutlet UIButton *soldButton;

@property (nonatomic, strong) NSArray *bookingSummaryDatas;
@property (nonatomic, strong) NSArray *cellDataArray;
@property (nonatomic, strong) Destination *selectedDeparture;
@property (nonatomic, strong) Destination *selectedArrival;
@property (nonatomic, assign) BOOL isSalesOnly;

@property (nonatomic, strong, readonly) NSArray *filterBookingSummaryDatas;

@end

@implementation ProductPickViewController

- (instancetype)init {
	// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
	if (self = [super init]) {
		self.edgesForExtendedLayout = UIRectEdgeNone;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];

	self.isSalesOnly = YES;
	self.title = self.service_date;

	self.departureButton.titleLabel.numberOfLines = 2;
	self.arrivalButton.titleLabel.numberOfLines = 2;
	self.soldButton.titleLabel.numberOfLines = 2;
	@weakify(self)
	[self.departureButton bk_addEventHandler:^(id sender) {
		@strongify(self)
		[self performSegueForFilterMode: BookingReportProductFilterModeDeparture];
	} forControlEvents: UIControlEventTouchUpInside];
	[self.arrivalButton bk_addEventHandler:^(id sender) {
		@strongify(self)
		[self performSegueForFilterMode: BookingReportProductFilterModeArrival];
	} forControlEvents:UIControlEventTouchUpInside];
	[self.soldButton bk_addEventHandler:^(id sender) {
		@strongify(self)
		[self performSegueForFilterMode: BookingReportProductFilterModeSalesOnly];
	} forControlEvents:UIControlEventTouchUpInside];
	[self reloadFilterToolbar];

	self.tableView.emptyDataSetSource = self;
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BookingReportProductListCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([BookingReportProductListCell class])];
}

- (void)viewDidLayoutSubviews {
	[super viewDidLayoutSubviews];

	[DrawUtils addBorderToRect:self.departureButton byEdges:UIRectEdgeRight strokeColor:[UIColor lightGrayColor]];
	[DrawUtils addBorderToRect:self.arrivalButton byEdges:UIRectEdgeRight strokeColor:[UIColor lightGrayColor]];
}

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

#pragma mark - Property

- (NSArray *)filterBookingSummaryDatas {
	NSMutableArray *array = [NSMutableArray arrayWithArray:self.bookingSummaryDatas];
	if (self.selectedDeparture) {
		[array bk_performSelect:^BOOL (VendorReportData *obj) {
			for (BusRoute *busRoute in [Vars appDelegate].loginUser.busRoutes) {
				if (busRoute.departure_object == self.selectedDeparture) {
					NSArray *pids = [[busRoute.pids_string componentsSeparatedByString:@","] valueForKeyPath:@"integerValue"];
					if ([pids containsObject:@(obj.product_id)]) {
						return YES;
					}
				}
			}
			return NO;
		}];
	}
	if (self.selectedArrival) {
		[array bk_performSelect:^BOOL (VendorReportData *obj) {
			for (BusRoute *busRoute in [Vars appDelegate].loginUser.busRoutes) {
				if (busRoute.arrival_object == self.selectedArrival) {
					NSArray *pids = [[busRoute.pids_string componentsSeparatedByString:@","] valueForKeyPath:@"integerValue"];
					if ([pids containsObject:@(obj.product_id)]) {
						return YES;
					}
				}
			}
			return NO;
		}];
	}
	if (self.isSalesOnly) {
		[array bk_performSelect:^BOOL (VendorReportData *obj) {
			return obj.sold_count > 0;
		}];
	}
	[array sortUsingComparator:^NSComparisonResult (VendorReportData *obj1, VendorReportData *obj2) {
		NSString *name1 = obj1.product.is_bus ? [NSString stringWithFormat:@"%@ %f => %@", obj1.product.firstDepartureStop.station.destination.show_name, obj1.product.listingHour, obj1.product.lastArrivalStop.station.destination.show_name] : obj1.product.name;
		NSString *name2 = obj2.product.is_bus ? [NSString stringWithFormat:@"%@ %f => %@", obj2.product.firstDepartureStop.station.destination.show_name, obj2.product.listingHour, obj2.product.lastArrivalStop.station.destination.show_name] : obj2.product.name;
		return [name1 localizedCaseInsensitiveCompare:name2];
	}];
	return [NSArray arrayWithArray:array];
}

#pragma mark - Segue

- (void)performSegueForDetailWithObject:(VendorReportData *)vendorReport {
	VendorReportController *viewController = [[VendorReportController alloc] init];
	viewController.data = vendorReport;
	viewController.service_date = self.service_date;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForFilterMode:(BookingReportProductFilterMode)filterMode {
	BookingReportProductFilterViewController *viewController = [[BookingReportProductFilterViewController alloc] initWithFilterMode:filterMode];
	viewController.selectedDeparture = self.selectedDeparture;
	viewController.selectedArrival = self.selectedArrival;
	viewController.isSalesOnly = self.isSalesOnly;
	[viewController setDidCancelBlock:^{
		[self.navigationController popViewControllerAnimated:YES];
	}];
	[viewController setDidDoneBlock:^(Destination *departure, Destination *arrival, BOOL isSalesOnly) {
		[self.navigationController popViewControllerAnimated:YES];
		self.selectedDeparture = departure;
		self.selectedArrival = arrival;
		self.isSalesOnly = isSalesOnly;
		[self reloadFilterToolbar];
		[self buildCellDataSource];
		[self.tableView reloadData];
	}];
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Network

- (void)bookingSummary {
	BookingSummary *summary = [[BookingSummary alloc] init];
	summary.date = self.service_date;

	NSDictionary *requestDict = [Utility perlParamXml:[summary innerXML] action:summary.name];
	self.tableView.emptyDataSetSource = nil;
	[Utility getXMLFromRequestWithMethod:@"GET" url:summary.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		BookingSummaryResponseJsonMapper *mapper = [[BookingSummaryResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			BookingSummaryResponse *response = mapper.response;
			if (![StringUtils isEmpty:response.error]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error];
			} else {
				self.bookingSummaryDatas = [self preInstallBookingSummaryDatas:response.datas];
				[self buildCellDataSource];
				self.tableView.emptyDataSetSource = self;
				[self.tableView reloadData];
			}
		}
	}];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *array = [NSMutableArray array];
	@weakify(self)
	for (VendorReportData *vendorReport in self.filterBookingSummaryDatas) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([BookingReportProductListCell class]);
		data.weaklyAssociatedObject = vendorReport;
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueForDetailWithObject: vendorReport];
		}];
		[array addObject:data];
	}
	self.cellDataArray = [NSArray arrayWithArray:array];
}

- (NSArray *)preInstallBookingSummaryDatas:(NSArray *)objs {
	NSDictionary *productHash = [NSDictionary dictionaryWithObjects:[Vars appDelegate].loginUser.products forKeys:[[Vars appDelegate].loginUser.products valueForKeyPath:@"product_id"]];
	NSMutableArray *array = [NSMutableArray array];
	for (VendorReportData *obj in objs) {
		Product *product = [productHash objectForKey:@(obj.product_id)];
		if (product) {
			obj.product = product;
			obj.bus_status_info.product = product;
			[array addObject:obj];
		}
	}
	return [NSArray arrayWithArray:array];
}

- (void)reloadFilterToolbar {
	if (YES) {
		NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Departure" attributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:self.selectedDeparture ? [Destination cityName:self.selectedDeparture.show_name] : @"ALL" attributes:@{NSForegroundColorAttributeName : [Vars defaultTintColor]}]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[attributedString appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome caretDownIconWithSize:self.departureButton.titleLabel.font.pointSize] fillColor:[UIColor lightGrayColor]]];
		[self.departureButton setAttributedTitle:attributedString forState:UIControlStateNormal];
	}
	if (YES) {
		NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Arrival" attributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:self.selectedArrival ? [Destination cityName:self.selectedArrival.show_name] : @"ALL" attributes:@{NSForegroundColorAttributeName : [Vars defaultTintColor]}]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[attributedString appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome caretDownIconWithSize:self.arrivalButton.titleLabel.font.pointSize] fillColor:[UIColor lightGrayColor]]];
		[self.arrivalButton setAttributedTitle:attributedString forState:UIControlStateNormal];
	}
	if (YES) {
		NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Sales Only" attributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:self.isSalesOnly ? @"YES" : @"NO" attributes:@{NSForegroundColorAttributeName : [Vars defaultTintColor]}]];
		[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
		[attributedString appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome caretDownIconWithSize:self.soldButton.titleLabel.font.pointSize] fillColor:[UIColor lightGrayColor]]];
		[self.soldButton setAttributedTitle:attributedString forState:UIControlStateNormal];
	}
}

#pragma mark - Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.cellDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([BookingReportProductListCell class])]) {
		return [UIToolkit instantiateRowHeightForTableViewCellWithNibName:NSStringFromClass([BookingReportProductListCell class])];
	}
	return [UIConstants defaultTableViewRowHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([BookingReportProductListCell class])]) {
		BookingReportProductListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BookingReportProductListCell class])];
		VendorReportData *obj = data.weaklyAssociatedObject;
		cell.nameLabel.text = obj.product.name;
		if (obj.product.schedule_id) {
			NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Bus ID" attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor]}]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:obj.product.schedule_id attributes:@{NSForegroundColorAttributeName : [UIColor darkGrayColor]}]];
			cell.scheduleIdLabel.attributedText = attributedString;
		} else if (obj.product.is_bus) {
			cell.scheduleIdLabel.text = @"Bus";
		} else if (obj.product.is_show) {
			cell.scheduleIdLabel.text = @"Show";
		} else if (obj.product.is_hotel) {
			cell.scheduleIdLabel.text = @"Hotel";
		}
		if (YES) {
			NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Sold" attributes:@{NSForegroundColorAttributeName : [UIColor lightGrayColor]}]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"%d", obj.sold_count] attributes:@{NSForegroundColorAttributeName : [UIColor darkGrayColor]}]];
			cell.soldLabel.attributedText = attributedString;
		}
		return cell;
	}
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

// Override to support row selection in the table view.
- (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
