//
// ReschedulePolicyViewController.m
// GotoBus
//
// Created by haibara on 1/22/15.
//
//

#import "ReschedulePolicyViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "DZNEmptyDataSetDefault.h"
#import <DTCoreText/DTCoreText.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "PerlWS.h"
#import "GetReschedulePolicyResponseJsonMapper.h"
#import "BusRescheduleViewController.h"
#import "Vars.h"

@interface ReschedulePolicyViewController () <UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetDefault>

@property (nonatomic, strong) GetReschedulePolicyResponse *getReschedulePolicyResponse;
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) NSArray *headerDataArray;

@end

@implementation ReschedulePolicyViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	if (YES) {
		UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
		button.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), [UIConstants defaultTableViewRowHeight]);
		button.backgroundColor = [Vars defaultTintColor];
		button.titleLabel.font = [UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
		[button setTitle:@"Next" forState:UIControlStateNormal];
		[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[button addTarget:self action:@selector(gotoNext) forControlEvents:UIControlEventTouchUpInside];
		[Utility addInsetToFooterViewIfSafeArea:button];
		self.fixedFooterView = button;
	}

	self.tableView.emptyDataSetSource = self;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	if (!self.getReschedulePolicyResponse) {
		[self getReschedulePolicy];
	}
}

#pragma mark - Action

- (void)gotoNext {
	if (self.getReschedulePolicyResponse) {
		BusRescheduleViewController *viewController = [[BusRescheduleViewController alloc] init];
		viewController.entry = self.entry;
		[self.navigationController pushViewController:viewController animated:YES];
	}
}

#pragma mark - Network

- (void)getReschedulePolicy {
	GetReschedulePolicy *getReschedulePolicy = [[GetReschedulePolicy alloc] init];
	getReschedulePolicy.itineraryNo = self.entry.entry_id;

	NSDictionary *requestDict = [Utility perlParamXml:[getReschedulePolicy innerXML] action:getReschedulePolicy.name];
	// NSLog(@"%@", requestDict);
	self.tableView.emptyDataSetSource = nil;
	[Utility getXMLFromRequestWithMethod:@"GET" url:getReschedulePolicy.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		GetReschedulePolicyResponseJsonMapper *mapper = [[GetReschedulePolicyResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetReschedulePolicyResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				self.getReschedulePolicyResponse = response;
				[self buildCellDataSource];
				[self buildHeaderDataSource];
				self.tableView.emptyDataSetSource = self;
				[self.tableView reloadData];
			}
		}
	}];
}

#pragma mark - Private

- (void)buildCellDataSource {
	NSMutableArray *arrays = [NSMutableArray array];
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.text = self.getReschedulePolicyResponse.header;
		data.allowsTextLineWrapping = YES;
		[arrays addObject:@[data]];
	}
	for (GetReschedulePolicyResponseSection *getReschedulePolicyResponseSection in self.getReschedulePolicyResponse.sections) {
		NSMutableArray *array = [NSMutableArray array];
		for (GetReschedulePolicyResponseLabel *getReschedulePolicyResponseLabel in getReschedulePolicyResponseSection.detailLabels) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			if (![StringUtils isEmpty:getReschedulePolicyResponseLabel.text]) {
				data.text = getReschedulePolicyResponseLabel.text;
				data.allowsTextLineWrapping = YES;
			} else if (![StringUtils isEmpty:getReschedulePolicyResponseLabel.html]) {
				data.reuseIdentifier = NSStringFromClass([DTAttributedTextCell class]);
				data.weaklyAssociatedObject = getReschedulePolicyResponseLabel.html;
			}
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

- (void)buildHeaderDataSource {
	NSMutableArray *array = [NSMutableArray array];
	if (YES) {
		TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
		[array addObject:data];
	}
	for (GetReschedulePolicyResponseSection *getReschedulePolicyResponseSection in self.getReschedulePolicyResponse.sections) {
		TableViewSectionHeaderFooterData *data = [[TableViewSectionHeaderFooterData alloc] init];
		if (![StringUtils isBlank:getReschedulePolicyResponseSection.titleLabel.text]) {
			data.title = getReschedulePolicyResponseSection.titleLabel.text;
		} else {
			data.title = @" ";
		}
		[array addObject:data];
	}
	self.headerDataArray = [NSArray arrayWithArray:array];
}

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

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

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

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([DTAttributedTextCell class])]) {
		return 100;
	}
	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.attributedTextContextView.edgeInsets = [UIConstants defaultTableViewCellLayoutInsets];
		[cell setHTMLString:data.weaklyAssociatedObject options:[self optionsForDisplayingHTMLString]];
		return cell;
	}
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

@end
