//
// BookingFinishViewController.m
// GoToBus
//
// Created by iphone development on 7/14/14.
//
//

#import "BookingFinishViewController.h"
#import "SDK.h"
#import "Lang.h"
#import "CocoaUtils.h"
#import "AppTracker.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import <ADAppRater/ADAppRater.h>
#import <BlocksKit/BlocksKit.h>
#import <DTCoreText/DTCoreText.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "TabBarViewController.h"
#import "Vars.h"

@interface BookingFinishViewController ()

@property (nonatomic, weak) IBOutlet UIImageView *checkmarkImageView;
@property (nonatomic, weak) IBOutlet DTAttributedLabel *postSaleAttributedLabel;
@property (nonatomic, weak) IBOutlet UILabel *postSaleLabel;
@property (nonatomic, weak) IBOutlet UILabel *eTicketLabel;
@property (nonatomic, weak) IBOutlet UIButton *summaryViewButton;
@property (nonatomic, weak) IBOutlet UIButton *cartEmptyButton;

- (IBAction)performActionForViewOrderSummary:(id)sender;
- (IBAction)performActionForEmptyCart;

@end

@implementation BookingFinishViewController

- (instancetype)init {
	self = [super init];
	if (self) {
		// Custom initialization
		self.title = IMLocalizedString(@"Finish");
		self.hidesBottomBarWhenPushed = YES;
		self.navigationItem.hidesBackButton = YES;
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view from its nib.
	[[AppTracker sharedInstance] sendView:[self class]];

	if (self.bookGoodsResponse.payment_accepted) {
		self.checkmarkImageView.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome checkCircleIconWithSize:CGRectGetHeight(self.checkmarkImageView.frame)] fillColor:[UIColor cloverColor]];
	} else {
		self.checkmarkImageView.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome exclamationCircleIconWithSize:CGRectGetHeight(self.checkmarkImageView.frame)] fillColor:[Vars defaultTintColor]];
	}
	self.postSaleAttributedLabel.layoutFrameHeightIsConstrainedByBounds = NO;
	if ([StringUtils isEmpty:self.customPostSaleText]) {
		self.postSaleAttributedLabel.attributedString = [[NSAttributedString alloc] initWithHTMLData:[self.bookGoodsResponse.post_sale_html dataUsingEncoding:NSUTF8StringEncoding] options:[self optionsForDisplayingHTMLString] documentAttributes:NULL];
		[self.view bringSubviewToFront:self.postSaleAttributedLabel];
		[self.view sendSubviewToBack:self.postSaleLabel];
	} else {
		self.postSaleLabel.text = self.customPostSaleText;
		[self.view bringSubviewToFront:self.postSaleLabel];
		[self.view sendSubviewToBack:self.postSaleAttributedLabel];
	}
	self.summaryViewButton.backgroundColor = [Vars defaultTintColor];
	[Utility addRoundedBorderToButton:self.summaryViewButton];
	if (self.bookGoodsResponse.payment_accepted) {
		if (self.bookGoodsResponse.etickets.count == 1) {
			self.summaryViewButton.hidden = NO;
			[self.summaryViewButton setTitle:IMLocalizedString(@"View E-Ticket") forState:UIControlStateNormal];
		} else if (self.bookGoodsResponse.order_summary) {
			self.summaryViewButton.hidden = NO;
			[self.summaryViewButton setTitle:IMLocalizedString(@"View Order Summary") forState:UIControlStateNormal];
		}
		NSMutableArray *buttons = [NSMutableArray array];
		if (self.bookGoodsResponse.etickets.count > 1) {
			self.eTicketLabel.hidden = NO;
			[self.bookGoodsResponse.etickets enumerateObjectsUsingBlock:^(_ETicket *eticket, NSUInteger idx, BOOL *stop) {
				UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
				button.backgroundColor = [Vars defaultTintColor];
				button.tag = idx;
				button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
				button.titleLabel.numberOfLines = 2;
				button.titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
				[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
				[button setTitle:[NSString stringWithFormat:@"%@ %@", eticket.date, eticket.name]
				forState:UIControlStateNormal];
				[button addTarget:self action:@selector(performActionForViewETicket:) forControlEvents:UIControlEventTouchUpInside];
				[self.view addSubview:button];
				[buttons addObject:button];
			}];
			[Utility addRoundedBorderToButtons:buttons];
			[buttons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) {
				[button autoAlignAxisToSuperviewAxis:ALAxisVertical];
				[button autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:30];
				[button autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:idx == 0 ? self.eTicketLabel : buttons[idx - 1] withOffset:idx == 0 ? 5 : 15];
				[button autoSetDimension:ALDimensionHeight toSize:[UIConstants defaultTableViewRowHeight]];
			}];
		} else {
			self.eTicketLabel.hidden = YES;
			[buttons addObject:self.summaryViewButton];
		}
		[self.cartEmptyButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:buttons.lastObject withOffset:15];
	} else {
		self.eTicketLabel.hidden = YES;
		self.summaryViewButton.hidden = YES;
	}
	self.cartEmptyButton.backgroundColor = [Vars defaultTintColor];
	[Utility addRoundedBorderToButton:self.cartEmptyButton];

	if ([Vars appDelegate].shopCarts.hasBusHotelPackage) {
		[self.cartEmptyButton setTitle:IMLocalizedString(@"Find Bus + Hotel") forState:UIControlStateNormal];
	} else {
		BOOL hasBus = [[Vars appDelegate].shopCarts.entries bk_any:^BOOL (CartEntry *obj) {
			return obj.product.is_bus;
		}];
		BOOL hasHotel = [[Vars appDelegate].shopCarts.entries bk_any:^BOOL (CartEntry *obj) {
			return obj.product.is_hotel;
		}];
		if (hasBus) {
			[self.cartEmptyButton setTitle:IMLocalizedString(@"Find Bus Tickets") forState:UIControlStateNormal];
		} else if (hasHotel) {
			[self.cartEmptyButton setTitle:IMLocalizedString(@"Find Hotels") forState:UIControlStateNormal];
		}
	}
}

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

	[Utility promptRatingOnceFromViewController:self];
}

#pragma mark - Action

- (IBAction)performActionForViewOrderSummary:(id)sender {
	IMWebViewController *viewController = nil;
	if (self.bookGoodsResponse.order_summary) {
		viewController = [[IMWebViewController alloc] initWithHTMLString:self.bookGoodsResponse.order_summary.html];
		viewController.title = IMLocalizedString(@"Order Summary");
	} else if (self.bookGoodsResponse.etickets.count > 0) {
		_ETicket *eticket = self.bookGoodsResponse.etickets.firstObject;
		viewController = [[IMWebViewController alloc] initWithHTMLString:eticket.html];
		viewController.title = IMLocalizedString(@"E-Ticket");
	}
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.autoshrink = YES;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performActionForViewETicket:(id)sender {
	UIButton *button = sender;
	_ETicket *eticket = self.bookGoodsResponse.etickets[button.tag];
	IMWebViewController *viewController = [[IMWebViewController alloc] initWithHTMLString:eticket.html];
	viewController.title = IMLocalizedString(@"E-Ticket");
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.autoshrink = YES;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (IBAction)performActionForEmptyCart {
	NSInteger selectIndex = 0;
	BOOL hasBusAndHotel = [Vars appDelegate].shopCarts.hasBusHotelPackage;
	BOOL hasBus = [[Vars appDelegate].shopCarts.entries bk_any:^BOOL (CartEntry *obj) {
		return obj.product.is_bus;
	}];
	BOOL hasHotel = [[Vars appDelegate].shopCarts.entries bk_any:^BOOL (CartEntry *obj) {
		return obj.product.is_hotel;
	}];
	if (hasBus) {
		selectIndex = 0;
	}
	//gotobus
	if ([[Vars appId] isEqualToString:@"334568970"]) {
		 if (hasHotel){
			selectIndex = 1;
		}else if (hasBusAndHotel){
			selectIndex = 2;
		}
	}
	
	//china town
	if ([[Vars appId] isEqualToString:@"1077208479"]) {
		if (hasBusAndHotel){
			selectIndex = 1;
		}
	}
	
	Class class = nil;
	class = self.navigationController.viewControllers.firstObject;
	if ([class isKindOfClass:NSClassFromString(@"HomeViewController")]) {
		[[NSNotificationCenter defaultCenter] postNotificationName:BookingFinishNotification object:@(selectIndex)];
	}
	[[Vars appDelegate].shopCarts empty];
	if ([Vars appDelegate].loginUser.app_first_purchase_discount_banner_shown) {
		[Vars appDelegate].loginUser.app_first_purchase_discount_banner_shown = NO;
	}
	[self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - Private

- (NSDictionary *)optionsForDisplayingHTMLString {
	UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
	return @{ DTUseiOS6Attributes : @YES, DTDefaultFontFamily : font.familyName, DTDefaultFontSize : @(font.pointSize), DTDefaultLinkDecoration : @NO };
}

@end
