//
// PaymentInfoViewController.m
// GotoBus
//
// Created by haibara on 3/6/15.
//
//

#import "PaymentInfoViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "Validator.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <BlocksKit/A2DynamicDelegate.h>
#import <BlocksKit/NSObject+A2DynamicDelegate.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "Vars.h"

@interface PaymentInfoViewController ()
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) NSArray *headerDataArray;
@property (nonatomic, strong) NSArray *footerDataArray;
@property (nonatomic, copy) void (^destructiveBlock) (void);
@end

@implementation PaymentInfoViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];
#if DEBUG
	if ([Vars is_develop]) {
		if (self.paymentInfo.credit_card && self.paymentInfo.credit_card.ccid == 0) {
			self.paymentInfo.credit_card = [CreditCard randomCreditCard];
		}
	}
#endif
	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:@"Submit" forState:UIControlStateNormal];
		[button addTarget:self action:@selector(submitForm) forControlEvents:UIControlEventTouchUpInside];
		[Utility addRoundedBorderToButton:button];
		[footerView addSubview:button];
		self.tableView.tableFooterView = footerView;
	}
	[self buildCellDataSource];
	[self buildHeaderFooterDataSource];
}

#pragma mark - Action

- (void)submitForm {
	if (![self validatePaymentInfo]) {
		return;
	}
	if (self.destructiveBlock) {
		self.destructiveBlock();
	}
}

#pragma mark - Private

- (void)buildHeaderFooterDataSource {
	NSMutableArray *array2 = [NSMutableArray array];
	NSMutableArray *array3 = [NSMutableArray array];
	for (int i = 0; i < self.paymentInfo.refund_transactions.count; i++) {
		if (YES) {
			TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
			if (i == 0) {
				data.title = self.paymentInfo.total_refund_message;
				data.preserveCase = YES;
			}
			[array2 addObject:data];
		}
		if (YES) {
			TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
			if (i == self.paymentInfo.refund_transactions.count - 1) {
				data.title = self.paymentInfo.global_refund_alert;
			}
			[array3 addObject:data];
		}
	}
	if (self.paymentInfo.credit_card) {
		if (YES) {
			TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
			data.title = self.paymentInfo.charge_message;
			data.preserveCase = YES;
			[array2 addObject:data];
		}
		if (YES) {
			TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
			[array3 addObject:data];
		}
	}
	self.headerDataArray = [NSArray arrayWithArray:array2];
	self.footerDataArray = [NSArray arrayWithArray:array3];
}

- (void)buildCellDataSource {
	NSMutableArray *array1 = [NSMutableArray array];
	if (YES) {
		for (_RefundTransaction *refundTransaction in self.paymentInfo.refund_transactions) {
			NSMutableArray *array = [NSMutableArray array];
			if (YES) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
				data.style = UITableViewCellStyleSubtitle;
				data.text = refundTransaction.merchant;
				data.detailText = @"Merchant";
				data.detailTextColor = [UIColor lightGrayColor];
				[array addObject:data];
			}
			if (YES) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
				data.style = UITableViewCellStyleSubtitle;
				data.text = [@"$" stringByAppendingFormat:@"%g", refundTransaction.refund_amount];
				data.detailText = @"Refund Amount";
				data.detailTextColor = [UIColor lightGrayColor];
				[array addObject:data];
			}
			if (!refundTransaction.not_credit_card) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
				data.style = UITableViewCellStyleSubtitle;
				data.detailText = @"Card Number";
				data.editingType = TableViewCellEditingTypeTextField;
				data.borderStyle = UITextBorderStyleBezel;
				data.placeholder = [NSString stringWithFormat:@"Last %d Digits", refundTransaction.last_digits_length];
				data.keyboardType = UIKeyboardTypeNumberPad;
				data.textContentType = IMTextContentTypeCreditCardNumber;
				UILabel *label = [[UILabel alloc] init];
				label.backgroundColor = [UIColor grayColor];
				label.textColor = [UIColor lightTextColor];
				label.text = refundTransaction.card_number;
				[label sizeToFit];
				label.frame = CGRectMake(0, 0, CGRectGetWidth(label.frame) + 5 * 2, [UIConstants defaultTextFieldHeight]);
				data.leftView = label;
				data.observedObject = refundTransaction;
				data.keyPath = @"last_digits";
				data.maxLength = refundTransaction.last_digits_length;
				data.isEditingRequired = YES;
				[data addIntegrityValidationRuleBlock:^BOOL {
					return refundTransaction.last_digits.length == refundTransaction.last_digits_length;
				} withMessageBlock:^NSString *{
					return [NSString stringWithFormat:@"Please enter %d digits long", refundTransaction.last_digits_length];
				}];
				[array addObject:data];
			}
			[array1 addObject:[NSArray arrayWithArray:array]];
		}
	}
	if (self.paymentInfo.credit_card) {
		[array1 addObject:[Utility collectTableViewCellDataArrayWithCreditCard:self.paymentInfo.credit_card]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:array1];
}

- (BOOL)validatePaymentInfo {
	[self.tableView endEditing:YES];
	for (int section = 0; section < self.cellDataArrays.count; section++) {
		for (int row = 0; row < [self.cellDataArrays[section] count]; row++) {
			NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
			TableViewCellData *data = self.cellDataArrays[section][row];
			if (![data validateRequired]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[data requiredValidationMessage:NO] dismissalHandler:^{
					[UIToolkit tableView:self.tableView atIndexPath:indexPath didFocusWithData:data];
				}];
				return NO;
			}
			if (![data validateIntegrity]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[data integrityValidationMessage:NO] dismissalHandler:^{
					[UIToolkit tableView:self.tableView atIndexPath:indexPath didFocusWithData:data];
				}];
				return NO;
			}
		}
	}
	return YES;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	TableViewSectionHeaderFooterData *data = self.headerDataArray[section];
	return [UIToolkit tableView:tableView inSection:section headerHeightWithData:data];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
	TableViewSectionHeaderFooterData *data = self.footerDataArray[section];
	return [UIToolkit tableView:tableView inSection:section headerTitleWithData:data];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	TableViewSectionHeaderFooterData *data = self.headerDataArray[section];
	return [UIToolkit tableView:tableView inSection:section headerViewWithData:data];
}

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

- (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 {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

@end
