//
// SoldStockListViewController.m
// GoToBus
//
// Created by iphone development on 6/6/14.
//
//

#import "SoldStockListViewController.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+UIKit.h>
#import <HMSegmentedControl/HMSegmentedControl.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "Sales.h"
#import "SoldStock.h"
#import "PerlWS.h"
#import "UIViewController+Privilege.h"
#import "PurchaseRecordResponseJsonMapper.h"
#import "CheckInActionHandler.h"
#import "SalesEntryDetailViewController.h"
#import "Vars.h"

@interface SoldStockListViewController () <DZNEmptyDataSetDefault>

@property (nonatomic, strong) NSMutableArray *selectedStocks;
@property (nonatomic, strong) NSArray *indexTitles;
@property (nonatomic, strong) NSArray *sortedArrays;

@property (nonatomic, strong) NSArray *cellDataArrays;

@property (nonatomic, strong) HMSegmentedControl *segmentControl;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *selectAllButton;
@property (nonatomic, strong) UIButton *checkInButton;
@property (nonatomic, strong) UIButton *undoButton;

@property (nonatomic, strong, readonly) NSArray *allStocks;
@property (nonatomic, strong, readonly) NSArray *usedStocks;
@property (nonatomic, strong, readonly) NSArray *checkedStocks;
@property (nonatomic, strong, readonly) NSArray *uncheckedStocks;

@end

@implementation SoldStockListViewController

- (instancetype)init {
	if (self = [super init]) {
		self.title = @"Sales Records";
		self.hidesBottomBarWhenPushed = YES;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	if (self.allowsCheckIn) {
		self.selectedStocks = [NSMutableArray array];

		self.navigationItem.rightBarButtonItem = self.editButtonItem;

		self.fixedHeaderView = self.segmentControl;

		if (YES) {
			@weakify(self)
			self.footerView = [[UIView alloc] init];
			self.footerView.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight]);
			self.footerView.backgroundColor = [UIColor whiteColor];

			self.selectAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
			self.selectAllButton.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
			self.selectAllButton.imageEdgeInsets = UIEdgeInsetsMake(0, -2, 0, 0);
			[self.selectAllButton setTitle:@"Select All" forState:UIControlStateNormal];
			[self.selectAllButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
			[self.selectAllButton setImage:[DrawUtils imageWithFAKIcon:[FAKIonIcons iosCircleOutlineIconWithSize:26] fillColor:[UIColor lightGrayColor]] forState:UIControlStateNormal];
			[self.selectAllButton setImage:[DrawUtils imageWithFAKIcon:[FAKIonIcons iosCheckmarkIconWithSize:26] fillColor:[Vars defaultTintColor]] forState:UIControlStateSelected];
			[self.selectAllButton bk_addEventHandler:^(UIButton *sender) {
				@strongify(self)
				sender.selected = !sender.selected;
				[self.selectedStocks removeAllObjects];
				if (sender.selected) {
					[self.selectedStocks addObjectsFromArray:self.usedStocks];
				}
				[self.tableView reloadData];
			} forControlEvents:UIControlEventTouchUpInside];

			self.checkInButton = [UIButton buttonWithType:UIButtonTypeCustom];
			self.checkInButton.backgroundColor = [Vars defaultTintColor];
			self.checkInButton.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
			[self.checkInButton setTitle:@"Check-In" forState:UIControlStateNormal];
			[self.checkInButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
			[self.checkInButton setTitleColor:[UIColor groupTableViewBackgroundColor] forState:UIControlStateDisabled];
			[self.checkInButton bk_addEventHandler:^(id sender) {
				@strongify(self)
				if (self.selectedStocks.count > 0) {
					[CheckInActionHandler updateStocks:self.selectedStocks toCheckIn:YES commit:^(NSString *message) {
						[self reloadSegmentTitles];
						[self updateSelectedStocks];
						[self makeIndexedCollation];
						[self buildCellDataSource];
						[self.tableView reloadData];
						[self reloadSelectionToolbar];
					}];
				} else {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select customer(s) first"];
				}
			} forControlEvents:UIControlEventTouchUpInside];
			[Utility addRoundedBorderToButton:self.checkInButton];

			self.undoButton = [UIButton buttonWithType:UIButtonTypeCustom];
			self.undoButton.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
			[self.undoButton setTitle:@"Undo" forState:UIControlStateNormal];
			[self.undoButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
			[self.undoButton setTitleColor:[UIColor groupTableViewBackgroundColor] forState:UIControlStateDisabled];
			[DrawUtils addRoundedBorderToRect:self.undoButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[Vars defaultTintColor]];
			[self.undoButton bk_addEventHandler:^(id sender) {
				@strongify(self)
				if (self.selectedStocks.count > 0) {
					[CheckInActionHandler updateStocks:self.selectedStocks toCheckIn:NO commit:^(NSString *message) {
						[self reloadSegmentTitles];
						[self updateSelectedStocks];
						[self makeIndexedCollation];
						[self buildCellDataSource];
						[self.tableView reloadData];
						[self reloadSelectionToolbar];
					}];
				} else {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:@"Please select customer(s) first"];
				}
			} forControlEvents:UIControlEventTouchUpInside];

			[self.footerView addSubview:self.selectAllButton];
			[self.footerView addSubview:self.checkInButton];
			[self.footerView addSubview:self.undoButton];

			[self.selectAllButton autoPinEdgeToSuperviewEdge:ALEdgeLeft];
			[self.selectAllButton autoPinEdgeToSuperviewEdge:ALEdgeTop];
			[self.selectAllButton autoPinEdgeToSuperviewEdge:ALEdgeBottom];
			[self.selectAllButton autoSetDimension:ALDimensionWidth toSize:120];

			[self.checkInButton autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.selectAllButton withOffset:5];
			[self.checkInButton autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:5];
			[self.checkInButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:5];

			[self.undoButton autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.checkInButton withOffset:5];
			[self.undoButton autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
			[self.undoButton autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:5];
			[self.undoButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:5];
			[self.undoButton autoMatchDimension:ALDimensionWidth toDimension:ALDimensionWidth ofView:self.checkInButton];
		}
	}
	self.tableView.emptyDataSetSource = self;

	self.editing = self.allowsCheckIn && self.isCheckIn;
}

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

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
	if (!self.allowsCheckIn) {
		return;
	}
	[super setEditing:editing animated:animated];

	self.editButtonItem.title = editing ? @"Done" : @"Check-In";
	self.fixedFooterView = editing ? self.footerView : nil;
	[self buildCellDataSource];
	[self.tableView reloadData];
	[self reloadSelectionToolbar];
	[self reloadBottomToolbar];
}

#pragma mark - Property

- (HMSegmentedControl *)segmentControl {
	if (!self.allowsCheckIn) {
		return nil;
	}
	if (!_segmentControl) {
		_segmentControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Total", @"Unchecked", @"Check-In"]];
		_segmentControl.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight]);
		_segmentControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
		_segmentControl.selectionIndicatorColor = [Vars defaultTintColor];
		_segmentControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
		@weakify(self)
		[_segmentControl setIndexChangeBlock:^(NSInteger index) {
			@strongify(self)
			[self updateSelectedStocks];
			[self makeIndexedCollation];
			[self buildCellDataSource];
			[self.tableView reloadData];
			[self reloadSelectionToolbar];
			[self reloadBottomToolbar];
		}];
		[_segmentControl setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {
			@strongify(self)
			NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] init];
			[attribute appendAttributedString:[[NSAttributedString alloc] im_initWithString:title attributes:@{NSForegroundColorAttributeName : [UIColor blackColor], NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]}]];
			[attribute appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[attribute appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"%d", [self getCurrentStocksWithIndex:index].count] attributes:@{NSForegroundColorAttributeName : [Vars defaultTintColor], NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote]}]];
			return [[NSAttributedString alloc] initWithAttributedString:attribute];
		}];
	}
	return _segmentControl;
}

- (NSArray *)checkedStocks {
	return [self.allStocks bk_select:^BOOL (SoldStock *obj) {
		return obj.vendor_checkin;
	}];
}

- (NSArray *)uncheckedStocks {
	return [self.allStocks bk_select:^BOOL (SoldStock *obj) {
		return !obj.vendor_checkin;
	}];
}

- (NSArray *)usedStocks {
	return [self getCurrentStocksWithIndex:self.segmentControl.selectedSegmentIndex];
}

- (NSArray *)allStocks {
	return [[[Sales toStocks:self.orders] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"hidden == NO"]] bk_select:^BOOL (SoldStock *obj) {
		return obj.entry.product.is_bus || obj.entry.product.is_show;
	}];
}

#pragma mark - Network

- (void)searchSales {
	SearchSales *searchSales = [[SearchSales alloc] init];
	searchSales.customer_name = self.inputCustomerName;
	searchSales.exact_email = self.email;
	searchSales.cn = self.inputCn;
	searchSales.date_from = self.startDate;
	searchSales.date_to = self.endDate;
	searchSales.date_type = self.date_type;
	searchSales.product_id = self.product_id;

	NSDictionary *requestDict = [Utility perlParamXml:[searchSales innerXML] action:searchSales.name];
	// NSLog(@"%@", requestDict);
	self.tableView.emptyDataSetSource = nil;
	[Utility getXMLFromRequestWithMethod:@"GET" url:searchSales.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.orders = response.orders;
				if (self.allowsCheckIn) {
					self.segmentControl.selectedSegmentIndex = 1;
					self.tableView.emptyDataSetSource = self;
					self.segmentControl.indexChangeBlock(self.segmentControl.selectedSegmentIndex);
				} else {
					[self makeIndexedCollation];
					[self buildCellDataSource];
					self.tableView.emptyDataSetSource = self;
					[self.tableView reloadData];
				}
			}
		}
	}];
}

#pragma mark - Segue

- (void)performSegueForSalesEntryDetailWithSoldStock:(SoldStock *)stock {
	SalesEntryDetailViewController *viewController = [[SalesEntryDetailViewController alloc] init];
	viewController.entry = stock.entry;
	viewController.stock_id = stock.stock_id;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (void)buildCellDataSource {
	@weakify(self)
	NSMutableArray *arrays = [NSMutableArray array];
	for (NSArray *stocks in self.sortedArrays) {
		NSMutableArray *array = [NSMutableArray array];
		for (SoldStock *stock in stocks) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleSubtitle;
			data.text = stock.sold_to_name;
			[data setDetailTextBlock:^NSString *{
				return stock.otherShortDescription;
			}];
			if (self.editing) {
				data.selectedBackgroundColor = [UIColor clearColor];
				[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];
					}
					[self reloadSelectionToolbar];
				}];
				[data setDidDeselectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
					@strongify(self)
					if ([self.selectedStocks containsObject:stock]) {
						[self.selectedStocks removeObject:stock];
					}
					[self reloadSelectionToolbar];
				}];
				[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.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
				[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
					@strongify(self)
					[self performSegueForSalesEntryDetailWithSoldStock: stock];
				}];
			}
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

- (void)makeIndexedCollation {
	IMLocalizedIndexedCollation *provider = [[IMLocalizedIndexedCollation alloc] initWithObjects:self.usedStocks sortedUsingSelector:@selector(sold_to_name)];
	self.indexTitles = provider.sectionIndexTitles;
	self.sortedArrays = provider.sectionSortedArrays;
}

- (void)updateSelectedStocks {
	[self.selectedStocks removeAllObjects];
	if (self.segmentControl.selectedSegmentIndex == 1) {
		[self.selectedStocks addObjectsFromArray:self.usedStocks];
	}
}

- (void)reloadSegmentTitles {
	[self.segmentControl setNeedsDisplay];
}

- (void)reloadSelectionToolbar {
	self.selectAllButton.selected = self.selectedStocks.count > 0 && self.selectedStocks.count == self.usedStocks.count;
}

- (void)reloadBottomToolbar {
	switch (self.segmentControl.selectedSegmentIndex) {
		case 1:
			self.checkInButton.enabled = YES;
			self.checkInButton.backgroundColor = [Vars defaultTintColor];
			self.undoButton.enabled = NO;
			[DrawUtils addRoundedBorderToRect:self.checkInButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[UIColor clearColor]];
			[DrawUtils addRoundedBorderToRect:self.undoButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:self.undoButton.currentTitleColor];
			break;

		case 2:
			self.checkInButton.enabled = NO;
			self.checkInButton.backgroundColor = [UIColor clearColor];
			self.undoButton.enabled = YES;
			[DrawUtils addRoundedBorderToRect:self.checkInButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:self.checkInButton.currentTitleColor];
			[Utility addRoundedBorderToView:self.undoButton];
			break;

		default:
			self.checkInButton.enabled = YES;
			self.checkInButton.backgroundColor = [Vars defaultTintColor];
			self.undoButton.enabled = YES;
			[DrawUtils addRoundedBorderToRect:self.checkInButton cornerRadius:kDefaultRoundedCornerRadius strokeColor:[UIColor clearColor]];
			[Utility addRoundedBorderToView:self.undoButton];
			break;
	}
}

- (NSArray *)getCurrentStocksWithIndex:(NSInteger)index {
	switch (index) {
		case 0:
			return self.allStocks;

		case 1:
			return self.uncheckedStocks;

		case 2:
			return self.checkedStocks;

		default:
			return nil;
	}
}

#pragma mark - Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return self.cellDataArrays.count;
}

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

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
	return self.indexTitles;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return self.indexTitles[section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

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

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didDeselectWithData:data];
}

@end
