//
// BusHotelPriceDetailViewController.m
// Project
//
// Created by Ziv on 16/2/26.
//
//

#import "BookingPriceDetailViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "AppTracker.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit.h>
#import "Utility.h"
#import "CustomIcons.h"
#import "Vars.h"

@interface BookingPriceDetailViewController ()
@property (nonatomic, assign, readonly) NSInteger selectedIndex;
@property (nonatomic, strong) NSMutableArray *cellDataArrays;
@end

@implementation BookingPriceDetailViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];
	
	[[AppTracker sharedInstance] sendView:[self class]];
	
	if ([Vars appDelegate].shopCarts.entries.count > 1) {
		UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultSegmentedControlHeight] + 15 * 2)];
		headerView.backgroundColor = [UIColor whiteColor];
		NSMutableArray *items = [NSMutableArray arrayWithObjects:@"DEPARTURE", @"RETURN", nil];
		if ([Vars appDelegate].shopCarts.hasBusHotelPackage) {
			[items addObject:@"HOTEL"];
		}
		UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
		segmentedControl.tag = NSStringFromClass([UISegmentedControl class]).hash;
		segmentedControl.frame = CGRectMake(15, 15, CGRectGetWidth([UIScreen mainScreen].bounds) - 15 * 2, [UIConstants defaultSegmentedControlHeight]);
		segmentedControl.selectedSegmentIndex = 0;
		[segmentedControl addTarget:self action:@selector(changedRT:) forControlEvents:UIControlEventValueChanged];
		[headerView addSubview:segmentedControl];
		self.tableView.tableHeaderView = headerView;
	}
	[self buildCellDataSource];
}

#pragma mark - Action

- (void)changedRT:(UISegmentedControl *)segmentedControl {
	[self updateTableViewCellDataArrayForSubtotal];
	[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Property

- (NSInteger)selectedIndex {
	UISegmentedControl *segmentedControl = [self.tableView.tableHeaderView viewWithTag:NSStringFromClass([UISegmentedControl class]).hash];
	return segmentedControl ? segmentedControl.selectedSegmentIndex : 0;
}

#pragma mark - Private

- (void)buildCellDataSource {
	self.cellDataArrays = [NSMutableArray array];
	[self updateTableViewCellDataArrayForSubtotal];
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (self.response.busRoundtripDiscount > 0) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			data.text = @"Roundtrip Discount";
			data.textColor = [UIColor cloverColor];
			data.detailText = [@"-" im_stringByAppendingString:[self.response currencyTextFromNumber:self.response.busRoundtripDiscount currencyCode:[Vars appDelegate].shopCarts.currency_code]];
			data.detailTextColor = [UIColor cloverColor];
			[array addObject:data];
		}
		if (self.response.busHotelPackageSaving > 0) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			data.text = @"Bus + Hotel Package Savings";
			data.textColor = [UIColor cloverColor];
			data.detailText = [@"-" im_stringByAppendingString:[self.response currencyTextFromNumber:self.response.busHotelPackageSaving currencyCode:[Vars appDelegate].shopCarts.currency_code]];
			data.detailTextColor = [UIColor cloverColor];
			[array addObject:data];
		}
		if ([Vars appDelegate].shopCarts.rmb_selected && self.response.second_currency_discount > 0) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			data.text = IMLocalizedString(@"RMB Discount");
			data.textColor = [UIColor cloverColor];
			data.detailText = [@"-" im_stringByAppendingString:self.response.secondCurrencyDiscountText];
			data.detailTextColor = [UIColor cloverColor];
			[array addObject:data];
		}
		if (self.response.app_first_purchase_discount > 0 || self.response.app_first_purchase_discount_rate > 0) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			data.text = IMLocalizedString(@"First Purchase Promotion");
			data.textColor = [UIColor cloverColor];
			if (self.response.app_first_purchase_discount > 0) {
				data.detailText = [@"-" im_stringByAppendingString:[self.response currencyTextFromNumber:self.response.app_first_purchase_discount currencyCode:[Vars appDelegate].shopCarts.currency_code]];
			} else if (self.response.app_first_purchase_discount_rate > 0) {
				data.detailText = [@"-" im_stringByAppendingString:[CocoaUtils percentStringWithNumber:@(self.response.app_first_purchase_discount_rate)]];
			}
			data.detailTextColor = [UIColor cloverColor];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] init];
			[attributedStr appendAttributedString:[[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"Total") attributes:@{ NSForegroundColorAttributeName : [UIColor darkGrayColor] }]];
			[attributedStr appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[attributedStr appendAttributedString:[[NSAttributedString alloc] im_initWithString:[self.response totalFareTextWithCurrencyCode:[Vars appDelegate].shopCarts.currency_code] attributes:@{ NSForegroundColorAttributeName : [Vars defaultTintColor] }]];
			data.detailAttributedText = attributedStr;
			[array addObject:data];
		}
		self.cellDataArrays[1] = [NSArray arrayWithArray:array];
	}
}

- (void)updateTableViewCellDataArrayForSubtotal {
	if ([Vars appDelegate].shopCarts.entries.count != self.response.entries.count) {
		return;
	}
	CartEntry *entry = [Vars appDelegate].shopCarts.entries[self.selectedIndex];
	_Entry *_entry = self.response.entries[self.selectedIndex];
	NSMutableArray *array = [NSMutableArray array];
	if (NO && _entry.is_dynamic_price) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleSubtitle;
		data.image = [DrawUtils tableViewCellImageWithFAKIcon:[CustomIcons dynamicPriceIconWithSize:24] fillColor:[CocoaUtils colorWithRGBs:StandardColorBlue]];
		data.text = @"Dynamic Price";
		data.detailText = @"Price not guaranteed until checkout is complete.";
		data.detailTextColor = [UIColor darkGrayColor];
		data.adjustsDetailTextFontSize = YES;
		[array addObject:data];
	}
	if (entry.product.is_bus) {
		for (GetProductOptionsResponsePeopleType *peopleType in _entry.people_types) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			data.text = IMLocalizedString(peopleType.name.capitalizedString);
			data.textColor = [UIColor darkGrayColor];
			data.detailText = [NSString stringWithFormat:@"%d x %@", [SoldStock filteredStocks:entry.stocks byBasedType:peopleType.name.capitalizedString].count, [self.response currencyTextFromNumber:peopleType.peoplePrice currencyCode:[Vars appDelegate].shopCarts.currency_code]];
			data.detailTextColor = [UIColor darkGrayColor];
			[array addObject:data];
		}
	} else if (entry.product.is_hotel) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleValue1;
		data.text = entry.shortDescription;
		data.textColor = [UIColor darkGrayColor];
		data.detailText = [self.response currencyTextFromNumber:_entry.total_charge + _entry.bus_hotel_package_saving - _entry.service_fee_and_tax currencyCode:[Vars appDelegate].shopCarts.currency_code];
		//data.detailText = [NSString stringWithFormat:@"%d x %d x %@", entry.roomCount, entry.nightCount, [self.response currencyTextFromNumber:(_entry.total_charge + _entry.bus_hotel_package_saving - _entry.service_fee_and_tax) / entry.roomCount / entry.nightCount currencyCode:[Vars appDelegate].shopCarts.currency_code]];
		data.detailTextColor = [UIColor darkGrayColor];
		[array addObject:data];
	}
	if (_entry.service_fee_and_tax > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleValue1;
		data.text = IMLocalizedString(@"Taxes & Fees");
		data.textColor = [UIColor darkGrayColor];
		data.detailText = [self.response currencyTextFromNumber:_entry.service_fee_and_tax currencyCode:[Vars appDelegate].shopCarts.currency_code];
		data.detailTextColor = [UIColor darkGrayColor];
		[array addObject:data];
	}
	if (_entry.coupon_discount > 0) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.style = UITableViewCellStyleValue1;
		data.text = IMLocalizedString(@"Coupon Discount");
		data.textColor = [UIColor cloverColor];
		data.detailText = [@"-" im_stringByAppendingString:[self.response currencyTextFromNumber:_entry.coupon_discount currencyCode:[Vars appDelegate].shopCarts.currency_code]];
		data.detailTextColor = [UIColor cloverColor];
		[array addObject:data];
	}
	if (NO && (_entry.non_refundable || _entry.paid_separately)) {
		NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
		if (_entry.non_refundable) {
			if (attributedString.length > 0) {
				[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
			}
			[attributedString appendAttributedString:[Utility attributedStringWithHtmlString:@"Tickets are <b>non-refundable</b> and <b>non-transferable</b>." fixAttributes:@{ NSFontAttributeName : [UIConstants defaultTableViewCellTextLabelFont:UITableViewCellStyleDefault] }]];
		}
		if (_entry.paid_separately) {
			if (attributedString.length > 0) {
				[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n"]];
			}
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"Your reservation is made directly with %@.", entry.product.vendor_obj.short_name]]];
		}
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome printIconWithSize:24] fillColor:[Vars defaultTintColor]];
		data.attributedText = [[NSAttributedString alloc] initWithAttributedString:attributedString];
		data.allowsTextLineWrapping = YES;
		[array addObject:data];
	}
	self.cellDataArrays[0] = [NSArray arrayWithArray:array];
}

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

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if (section == 1) {
		return @" ";
	}
	return nil;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	if (section == 1) {
		return [UIConstants defaultTableViewSectionHeight:tableView.style];
	}
	return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
