//
// CheckInResultViewController.m
// GoToBus
//
// Created by iphone development on 3/11/13.
// Copyright 2013 __MyCompanyName__. All rights reserved.
//

#import "CheckInResultViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "TableViewCellWrapper.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "Product.h"
#import "SoldStock.h"
#import "UIViewController+Privilege.h"
#import "PurchaseRecordResponseJsonMapper.h"
#import "PerlWS.h"
#import "CheckInActionHandler.h"
#import "CheckInScanViewController.h"
#import "SalesEntryDetailViewController.h"
#import "Vars.h"

@interface CheckInResultViewController ()

@property (nonatomic, weak) IBOutlet TableViewCellWrapper *stockCellView;
@property (nonatomic, weak) IBOutlet UILabel *messageLabel;
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UIButton *actionButton;
@property (nonatomic, weak) IBOutlet UIButton *scanButton;

@property (nonatomic, strong) Sales *order;
@property (nonatomic, strong, readonly) SalesEntry *entry;

@property (nonatomic, strong, readonly) UITableViewCell *stockCell;

- (IBAction)toggleCheckIn:(id)sender;
- (IBAction)popToParent:(id)sender;

@end

@implementation CheckInResultViewController

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (instancetype)init {
	if (self = [super init]) {
		// Custom initialization
		self.edgesForExtendedLayout = UIRectEdgeNone;
		self.title = @"Check-In";
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

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

	@weakify(self)
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] im_initWithBarButtonSystemItem:UIBarButtonSystemItemCancel handler:^(UIBarButtonItem *barButtonItem) {
		@strongify(self)
		[self.navigationController popToRootViewControllerAnimated: YES];
	}];

	self.stockCellView.style = UITableViewCellStyleSubtitle;
	[self.stockCellView addGestureRecognizer:[UITapGestureRecognizer bk_recognizerWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
		@strongify(self)
		if (self.entry) {
			[self showDetail];
		} else {
			[self findUniqueOrder];
		}
	}]];
	self.stockCell.textLabel.textColor = [Vars defaultTintColor];
	self.stockCell.detailTextLabel.textColor = [Vars defaultTintColor];
	self.stockCell.accessoryView = [DrawUtils tableViewCellAccessoryDisclosureIndicatorRightWithColor:[Vars defaultTintColor]];
	[Utility addRoundedBorderToView:self.stockCellView];

	self.actionButton.backgroundColor = [Vars defaultTintColor];
	self.scanButton.backgroundColor = [Vars defaultTintColor];
	[Utility addRoundedBorderToButtons:@[self.actionButton, self.scanButton]];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];

	[self notifyTicketStatus:[self lookupStock:self.entry.stocks] reverse:NO];
	[self performSelector:@selector(processData)];
}

#pragma mark - Action

- (IBAction)toggleCheckIn:(id)sender {
	[CheckInActionHandler updateStocks:@[self.stock] toCheckIn:!self.stock.vendor_checkin commit:^(NSString *message) {
		[self performSelector:@selector(processData)];
	}];
}

- (IBAction)popToParent:(id)sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)showDetail {
	[self notifyTicketStatus:[self lookupStock:self.entry.stocks] reverse:YES];
	SalesEntryDetailViewController *viewController = [[SalesEntryDetailViewController alloc] init];
	viewController.entry = self.entry;
	viewController.stock_id = self.stock.stock_id;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Property

- (SalesEntry *)entry {
	return [self.order.entries bk_match:^BOOL (SalesEntry *obj) {
		return [obj.stocks bk_any:^BOOL (SoldStock *obj) {
			return obj.stock_id == self.stock.stock_id;
		}];
	}];
}

- (UITableViewCell *)stockCell {
	return [self.stockCellView get];
}

#pragma mark - Network

- (void)findUniqueOrder {
	FindUniqueOrder *record = [[FindUniqueOrder alloc] init];
	record.stock_id = self.stock.stock_id;

	NSDictionary *requestDict = [Utility perlParamXml:[record innerXML] action:record.name];

	[Utility getXMLFromRequestWithMethod:@"GET" url:record.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;

		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 {
				if (response.orders.count > 0) {
					self.order = response.orders.firstObject;
				}
				if (self.entry) {
					[self showDetail];
				} else {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:[Vars responseException]];
				}
			}
		}
	}];
}

#pragma mark - Private

- (void)processData {
	TicketStatus tStatus = [self lookupTicketStatus:self.stock];
	CheckInStatus cStatus = [self lookupCheckInStatus:self.stock];
	if (tStatus == TicketStatusNormal && cStatus == CheckInStatusYes && self.stock.checked) {
		self.imageView.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome checkCircleIconWithSize:CGRectGetHeight(self.imageView.frame)] fillColor:[UIColor cloverColor]];
		self.messageLabel.textColor = [UIColor cloverColor];
	} else {
		self.imageView.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome timesCircleIconWithSize:CGRectGetHeight(self.imageView.frame)] fillColor:[Vars defaultTintColor]];
		self.messageLabel.textColor = [Vars defaultTintColor];
	}
	if (cStatus == CheckInStatusNo) {
		self.actionButton.hidden = NO;
		[self.actionButton setTitle:@"Check-In" forState:UIControlStateNormal];
	} else if (cStatus == CheckInStatusYes) {
		self.actionButton.hidden = NO;
		[self.actionButton setTitle:@"Undo Check-In" forState:UIControlStateNormal];
	} else if (cStatus == CheckInStatusInvalid) {
		self.actionButton.hidden = YES;
	}
	if (tStatus != TicketStatusInvalid) {
		self.stockCell.hidden = NO;
		self.stockCell.textLabel.text = self.stock.sold_to_name;
		self.stockCell.detailTextLabel.text = self.stock.otherShortDescription;
	} else {
		self.stockCell.hidden = YES;
	}
	if (tStatus == TicketStatusInvalid) {
		self.messageLabel.text = @"The ticket is not valid";
	} else {
		NSMutableString *string = [NSMutableString string];
		if (cStatus == CheckInStatusYes) {
			if (self.stock.checked) {
				[string im_appendString:@"The ticket is checked in"];
			} else {
				[string im_appendString:@"The ticket is already checked in"];
			}
		} else if (cStatus == CheckInStatusNo) {
			[string im_appendString:@"The ticket is unchecked in"];
		}
		if (tStatus == TicketStatusNormal && cStatus == CheckInStatusYes) {
		} else if (tStatus == TicketStatusExpired) {
			[string appendFormat:@" and is expired on %@", self.stock.service_date];
		} else if (tStatus == TicketStatusComing) {
			[string appendFormat:@" and is upcoming on %@", self.stock.service_date];
		} else if (tStatus == TicketStatusOther) {
			[string im_appendString:@" and is not matched this bus schedule"];
		}
		self.messageLabel.text = string;
	}
}

- (void)notifyTicketStatus:(SoldStock *)stock reverse:(BOOL)reverse {
	if (stock) {
		if (reverse) {
			stock.vendor_checkin = self.stock.vendor_checkin;
			stock.checked = self.stock.checked;
		} else {
			self.stock.vendor_checkin = stock.vendor_checkin;
			self.stock.checked = stock.checked;
		}
	}
}

- (SoldStock *)lookupStock:(NSArray *)stocks {
	return [stocks bk_match:^BOOL (SoldStock *obj) {
		return obj.stock_id == self.stock.stock_id;
	}];
}

- (TicketStatus)lookupTicketStatus:(SoldStock *)stock {
	if (!stock) {
		return TicketStatusInvalid;
	} else {
		if (stock.product_id == self.product_id) {
			if ([stock.service_date compare:self.service_date] == NSOrderedAscending) {
				return TicketStatusExpired;
			} else if ([stock.service_date compare:self.service_date] == NSOrderedDescending) {
				return TicketStatusComing;
			}
			return TicketStatusNormal;
		} else {
			return TicketStatusOther;
		}
	}
}

- (CheckInStatus)lookupCheckInStatus:(SoldStock *)stock {
	if (!stock) {
		return CheckInStatusInvalid;
	} else {
		if (stock.vendor_checkin) {
			return CheckInStatusYes;
		} else {
			return CheckInStatusNo;
		}
	}
}

@end
