//
// TourSearchSubDetailVC.m
// IvyMedia
//
// Created by paul on 9/15/14.
//
//

#import "TourSearchSubDetailVC.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit.h>
#import <DTCoreText/DTCoreText.h>
#import <libextobjc/EXTScope.h>
#import "Utility.h"
#import "TourSearchDetailRichFoldingCell.h"
#import "Vars.h"

@interface TourSearchSubDetailVC ()
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) NSArray *indexTitles;
@end

@implementation TourSearchSubDetailVC

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

- (void)viewDidLoad {
	[super viewDidLoad];

	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TourSearchDetailRichFoldingCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([TourSearchDetailRichFoldingCell class])];
	[self buildCellDataSource];
}
 
#pragma mark - Private

- (void)buildCellDataSource {
	BOOL hasIndex = self.dailyTrips.count > 1;
	NSMutableArray *array = [NSMutableArray array];
	if (hasIndex) {
		if (self.topDescription) {
			[array addObject:@""];
		}
		[array addObjectsFromArray:[self.dailyTrips valueForKeyPath:@"nth_day.description"]];
		if (self.bottomDescription) {
			[array addObject:@""];
		}
	}
	self.indexTitles = [NSArray arrayWithArray:array];

	NSMutableArray *arrays = [NSMutableArray array];
	if (self.topDescription) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([DTAttributedTextCell class]);
		data.weaklyAssociatedObject = self.topDescription;
		[arrays addObject:@[data]];
	}
	if (!hasIndex) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([DTAttributedTextCell class]);
		data.weaklyAssociatedObject = [self.dailyTrips.firstObject content];
		[arrays addObject:@[data]];
	} else {
		for (GetTourDetailsResponseDailyTrip *dailyTrip in self.dailyTrips) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([TourSearchDetailRichFoldingCell class]);
			data.weaklyAssociatedObject = dailyTrip;
			data.stronglyAssociatedObject = @NO;
			[data setNeedLayoutFittingHeight];
			[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data){
				return [NSString stringWithFormat:@"%@", data.stronglyAssociatedObject];
			}];
			[arrays addObject:@[data]];
		}
	}
	if (self.bottomDescription) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([DTAttributedTextCell class]);
		data.weaklyAssociatedObject = self.bottomDescription;
		[arrays addObject:@[data]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

- (NSString *)wrapCSSAroundHTMLString:(NSString *)string {
	UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1];
	return [NSString stringWithFormat:@"<html><head><style type=\"text/css\">"
									  @"body,h2{font-family:\"%@\";font-size:%fpx;}"
									  @"li{padding:5px 0 0 0 !important;}"
									  @"img{display:none;}"
									  @".no_list_style{list-style:none;padding:0;margin:0;}"
									  @".d_instruction{background:#f5f5f6;padding:5px;margin:5px 0;}"
									  @".cf60{color:#ff6600;}"
									  @"</style></head><body>%@</body></html>", font.familyName, font.pointSize, string];
}

- (NSDictionary *)optionsForDisplayingHTMLString {
	UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1];
	NSString *CSSString = [NSString stringWithFormat:@"h2{font-family:\"%@\";font-size:%fpx;}"
													 @".no_list_style{list-style:none;padding:0;margin:0;}"
													 @".d_instruction{background:#f5f5f6;padding:5px;margin:5px;}"
													 @".cf60{color:#ff6600;}", font.familyName, font.pointSize];
	return @{ DTUseiOS6Attributes : @YES, DTDefaultFontFamily : font.familyName, DTDefaultFontSize : @(font.pointSize), DTDefaultLinkDecoration : @NO, DTDefaultStyleSheet : [[DTCSSStylesheet alloc] initWithStyleBlock:CSSString] };
}

- (void)changeAccordionActive:(BOOL)active onTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)newIndexPath {
	NSMutableArray *indexPaths = [NSMutableArray array];
	for (int section = 0; section < self.cellDataArrays.count; section++) {
		for (int row = 0; row < [self.cellDataArrays[section] count]; row++) {
			TableViewCellData *data = self.cellDataArrays[section][row];
			NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
			if ([data.reuseIdentifier isEqualToString:NSStringFromClass([TourSearchDetailRichFoldingCell class])]) {
				if ([indexPath isEqual:newIndexPath]) {
					data.stronglyAssociatedObject = @(active);
					[indexPaths addObject:newIndexPath];
				} else if (active) {
					if ([data.stronglyAssociatedObject boolValue]) {
						data.stronglyAssociatedObject = @NO;
						if ([tableView.indexPathsForVisibleRows containsObject:indexPath]) {
							[indexPaths addObject:indexPath];
						}
					}

				}
			}
		}
	}
	[tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

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

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([DTAttributedTextCell class])]) {
		return 100;
	} else if ([data.reuseIdentifier isEqualToString:NSStringFromClass([TourSearchDetailRichFoldingCell class])]) {
		return [UIToolkit instantiateRowHeightForTableViewCellWithNibName:NSStringFromClass([TourSearchDetailRichFoldingCell class])];
	}
	return [UIConstants defaultTableViewRowHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([DTAttributedTextCell class])]) {
		DTAttributedTextCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
		return [cell requiredRowHeightInTableView:tableView];
	}
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([DTAttributedTextCell class])]) {
		DTAttributedTextCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DTAttributedTextCell class])];
		if (cell == nil) {
			cell = [[DTAttributedTextCell alloc] initWithReuseIdentifier:NSStringFromClass([DTAttributedTextCell class])];
		}
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.attributedTextContextView.shouldDrawImages = NO;
		cell.attributedTextContextView.edgeInsets = [UIConstants defaultTableViewCellLayoutInsets];
		[cell setHTMLString:data.weaklyAssociatedObject options:[self optionsForDisplayingHTMLString]];
		return cell;
	} else if ([data.reuseIdentifier isEqualToString:NSStringFromClass([TourSearchDetailRichFoldingCell class])]) {
		TourSearchDetailRichFoldingCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([TourSearchDetailRichFoldingCell class])];
		UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
		GetTourDetailsResponseDailyTrip *dailyTrip = data.weaklyAssociatedObject;
		if (YES) {
			NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
			[attributedString appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome mapMarkerIconWithSize:font.pointSize] fillColor:[UIColor lightGrayColor]]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:IMLocalizedString(@"Day %d"), dailyTrip.nth_day] attributes:@{ NSForegroundColorAttributeName : [Vars defaultTintColor] }]];
			cell.titleLabel.font = font;
			cell.titleLabel.attributedText = [[NSAttributedString alloc] initWithAttributedString:attributedString];
		}
		cell.subtitleLabel.text = dailyTrip.title;
		cell.subtitleLabel.font = font;
		cell.subtitleLabel.textColor = [Vars defaultTintColor];
		[cell setHTMLString:dailyTrip.content options:[self optionsForDisplayingHTMLString]];
		cell.folding = [data.stronglyAssociatedObject boolValue];
		[cell ready];
		@weakify(self, tableView)
		[cell setToggleHandler:^(BOOL folding) {
			@strongify(self, tableView)
			[self changeAccordionActive: folding onTableView: tableView atIndexPath: indexPath];
		}];
		return cell;
	}
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

@end
