//
// TourSearchReviewListViewController.m
// Project
//
// Created by Ziv on 16/4/28.
//
//

#import "TourSearchReviewListViewController.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import "DZNEmptyDataSetDefault.h"
#import "MJRefreshLocalization.h"
#import <libextobjc/EXTScope.h>
#import <MJRefresh/MJRefresh.h>
#import "Utility.h"
#import "PerlWS.h"
#import "GetTourReviewsResponseJsonMapper.h"
#import "CustomReviewCell.h"
#import "LoginViewController.h"
#import "TourSearchReviewDetailViewController.h"
#import "Vars.h"

@interface TourSearchReviewListViewController () <DZNEmptyDataSetDefault, DZNEmptyDataSetDelegate>
@property (nonatomic, assign) NSInteger pageNo;
@property (nonatomic, strong) NSMutableArray *cellDataArray;
@property (nonatomic, strong) NSMutableArray *reviews;
@end

@implementation TourSearchReviewListViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.reviews = [NSMutableArray array];
	self.cellDataArray = [NSMutableArray array];

	[self updateReviewsTitle];

	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(writeReview)];

	self.tableView.emptyDataSetSource = self;
	self.tableView.emptyDataSetDelegate = self;
	[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CustomReviewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([CustomReviewCell class])];

	@weakify(self)
	MJRefreshNormalHeader * refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
		@strongify(self)
		self.pageNo = 0;
		[self getTourReviews:YES];
	}];
	refreshHeader.automaticallyChangeAlpha = YES;
	refreshHeader.lastUpdatedTimeLabel.hidden = YES;
	self.tableView.mj_header = refreshHeader;
	MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
		@strongify(self)
		[self getTourReviews: YES];
	}];
	refreshFooter.automaticallyChangeAlpha = YES;
	self.tableView.mj_footer = refreshFooter;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	// ajax
	if (self.pageNo == 0) {
		[self getTourReviews:NO];
	}
}

#pragma mark - Action

- (void)writeReview {
	if ([Vars appDelegate].loginUser) {
		[self performSegueForReviewEditing];
	} else {
		LoginViewController *viewController = [[LoginViewController alloc] init];
		[viewController performSegueWithObject:nil popAnimated:NO];
		[viewController setDestructiveBlock:^{
			[self performSegueForReviewEditing];
		}];
		[self.navigationController pushViewController:viewController animated:YES];
		
	}
}

#pragma mark - Segue

- (void)performSegueForReviewEditing {
	TourSearchReviewDetailViewController *viewController = [[TourSearchReviewDetailViewController alloc] init];
	viewController.tourCode = self.tourCode;
	viewController.isOneDay = self.isOneDay;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Network

- (void)getTourReviews:(BOOL)circle {
	BOOL initial = self.pageNo == 0;

	GetTourReviews *getTourReviews = [[GetTourReviews alloc] init];
	getTourReviews.tourCode = self.tourCode;
	getTourReviews.pageNo = ++self.pageNo;

	NSDictionary *requestDict = [Utility perlParamXml:[getTourReviews innerXML] action:getTourReviews.name];

	[Utility getXMLFromRequestWithMethod:@"GET" url:getTourReviews.address parameters:requestDict beforeSend:^{
		if (!circle) {
			[CocoaUtils showBusyIndicator:self.view];
			self.tableView.mj_header.hidden = YES;
			self.tableView.mj_footer.hidden = YES;
		}
		self.tableView.emptyDataSetSource = nil;
		self.tableView.emptyDataSetDelegate = nil;
	} success:^(NSString *xml) {
		// NSLog(@"%@", xml);
		if (initial) {
			[self.reviews removeAllObjects];
			[self.cellDataArray removeAllObjects];
		}
		GetTourReviewsResponseJsonMapper *mapper = [[GetTourReviewsResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:xml objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetTourReviewsResponse *response = mapper.response;
			self.reviewTotal = response.total_count;
			if (self.reviewTotal == 0) {
				[self.reviews removeAllObjects];
				[self.cellDataArray removeAllObjects];
			} else {
				[self.reviews addObjectsFromArray:response.reviews];
				[self updateTableViewCellDataArrayByReviews:response.reviews];
			}
		}
		self.tableView.emptyDataSetSource = self;
		self.tableView.emptyDataSetDelegate = self;
		[self.tableView reloadData];
		if (initial) {
			[self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
		}
		[self updateReviewsTitle];
	} complete:^{
		if (!circle) {
			if (self.reviews.count >= self.reviewTotal) {
				[self.tableView.mj_footer endRefreshingWithNoMoreData];
				self.tableView.mj_footer.hidden = YES;
			} else {
				[self.tableView.mj_footer resetNoMoreData];
				self.tableView.mj_footer.hidden = NO;
			}
		} else {
			[self.tableView.mj_header endRefreshing];
			if (self.reviews.count >= self.reviewTotal) {
				[self.tableView.mj_footer endRefreshingWithNoMoreData];
				self.tableView.mj_footer.hidden = YES;
			} else {
				[self.tableView.mj_footer endRefreshing];
				self.tableView.mj_footer.hidden = NO;
			}
		}
		if (!circle) {
			self.tableView.mj_header.hidden = NO;
			[CocoaUtils hideBusyIndicator:self.view];
		}
	}];
}

#pragma mark - Private

- (void)updateTableViewCellDataArrayByReviews:(NSArray *)reviews {
	NSMutableArray *array = [NSMutableArray array];
	for (TourReview *review in reviews) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseIdentifier = NSStringFromClass([CustomReviewCell class]);
		data.weaklyAssociatedObject = review;
		data.stronglyAssociatedObject = @NO;
		[data setNeedLayoutFittingHeight];
		[data setVaryingHeightIdentifierBlock:^NSString *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			return [NSString stringWithFormat:@"%@", data.stronglyAssociatedObject];
		}];
		[array addObject:data];
	}
	[self.cellDataArray addObjectsFromArray:array];
}

- (void)updateReviewsTitle {
	NSMutableString *string = [NSMutableString im_stringWithString:IMLocalizedString(@"Reviews")];
	if (self.reviewTotal > 0) {
		[string im_appendString:IMLocalizedString(WORD_DIVIDER_SPACE)];
		[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_LEFT)];
		[string appendFormat:@"%d", self.reviewTotal];
		[string im_appendString:IMLocalizedString(PUNCTUATION_PARENTHESES_RIGHT)];
	}
	self.title = [NSString stringWithString:string];
}

- (void)changeAccordionActive:(BOOL)active onTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)newIndexPath {
	NSMutableArray *indexPaths = [NSMutableArray array];
	for (int row = 0; row < self.cellDataArray.count; row++) {
		TableViewCellData *data = self.cellDataArray[row];
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
		if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomReviewCell 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 data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.cellDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	if ([data.reuseIdentifier isEqualToString:NSStringFromClass([CustomReviewCell class])]) {
		CustomReviewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomReviewCell class])];
		TourReview *review = data.weaklyAssociatedObject;
		cell.starRatingView.value = review.rating;
		if (review.recommend) {
			NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] init];
			[attributed appendAttributedString:[DrawUtils attributedStringWithFAKIcon:[FAKFontAwesome checkIconWithSize:cell.reCommendLabel.font.pointSize] fillColor:[CocoaUtils colorWithRGBs:StandardColorOrange]]];
			[attributed appendAttributedString:[[NSAttributedString alloc] im_initWithString:@" "]];
			[attributed appendAttributedString:[[NSAttributedString alloc] im_initWithString:IMLocalizedString(@"I recommend this tour!")]];
			cell.reCommendLabel.attributedText = attributed;
		} else {
			cell.reCommendLabel.attributedText = nil;
		}
		cell.postInfoLabel.text = [NSString stringWithFormat:IMLocalizedString(@"Posted by: %@ on %@"), review.full_name, [review.post_time substringToIndex:10]];
		cell.contentLabel.text = review.content;
		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];
}

#pragma mark - Table view delegate

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

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

#pragma mark - <DZNEmptyDataSetDelegate>

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
	return YES;
}

@end
