//
// BusVendorReviewListViewController.m
// Project
//
// Created by Ziv on 16/11/4.
//
//

#import "BusVendorReviewListViewController.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIToolkit.h"
#import "UIConstants.h"
#import "DZNEmptyDataSetDefault.h"
#import "MJRefreshLocalization.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <MJRefresh/MJRefresh.h>
#import <HCSStarRatingView/HCSStarRatingView.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "PerlWS.h"
#import "GetBusVendorReviewsResponseJsonMapper.h"
#import "CustomReviewCell.h"
#import "BusVendorReviewSummaryViewController.h"
#import "Vars.h"

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

@implementation BusVendorReviewListViewController

- (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] initWithImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome ellipsisHIconWithSize:24] fillColor:[UIColor whiteColor]] style:UIBarButtonItemStylePlain target:self action:@selector(performSegueForReviewSummary)];

	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 getBusVendorReviews:YES];
	}];
	refreshHeader.automaticallyChangeAlpha = YES;
	refreshHeader.lastUpdatedTimeLabel.hidden = YES;
	self.tableView.mj_header = refreshHeader;
	MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
		@strongify(self)
		[self getBusVendorReviews: YES];
	}];
	refreshFooter.automaticallyChangeAlpha = YES;
	self.tableView.mj_footer = refreshFooter;
}

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

#pragma mark - Segue

- (void)performSegueForReviewSummary {
	BusVendorReviewSummaryViewController *viewController = [[BusVendorReviewSummaryViewController alloc] init];
	viewController.summary = self.summary;
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Action

- (void)tapAccessoryButton:(UIButton *)button withBusVendorReview:(BusVendorReview *)review {
	UIView *contentView = [[UIView alloc] init];
	contentView.backgroundColor = [UIColor whiteColor];

	NSArray *titles = @[@"Bus Cleanliness", @"Punctuality", @"Service & Staff", @"Comfort"];
	NSArray *ratings = @[@(review.cleanliness_rating), @(review.punctuality_rating), @(review.service_rating), @(review.comfort_rating)];
	NSMutableArray *labels = [NSMutableArray array];
	[titles enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL *stop) {
		UILabel *label = [[UILabel alloc] init];
		label.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
		label.text = title;
		[contentView addSubview:label];
		[labels addObject:label];
		HCSStarRatingView *starRatingView = [[HCSStarRatingView alloc] init];
		[CocoaUtils configureStarRatingView:starRatingView editing:NO];
		starRatingView.tintColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
		starRatingView.value = [ratings[idx] floatValue];
		[contentView addSubview:starRatingView];

		[label autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:5];
		[starRatingView autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:label withOffset:5 relation:NSLayoutRelationGreaterThanOrEqual];
		[starRatingView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:5];
		[starRatingView autoSetDimensionsToSize:CGSizeMake(label.font.pointSize * 5.5, label.font.pointSize)];
		[starRatingView autoAlignAxis:ALAxisHorizontal toSameAxisOfView:label];
	}];
	[CocoaUtils autoVerticalDistributionToSubviews:labels spacing:5];

	contentView.frame = CGRectSetSize(contentView.frame, [contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]);

	[CocoaUtils showTooltipWithCustomView:contentView inView:self.view atFrame:[button convertRect:button.bounds toView:self.view]];
}

#pragma mark - Network

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

	GetBusVendorReviews *getReviews = [[GetBusVendorReviews alloc] init];
	getReviews.vendorId = self.vendorId;
	getReviews.pageNo = ++self.pageNo;

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

	[Utility getXMLFromRequestWithMethod:@"GET" url:getReviews.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) {
		if (initial) {
			[self.reviews removeAllObjects];
			[self.cellDataArray removeAllObjects];
		}
		GetBusVendorReviewsResponseJsonMapper *mapper = [[GetBusVendorReviewsResponseJsonMapper alloc] init];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:xml objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetBusVendorReviewsResponse *response = mapper.response;
			self.summary = response.reviews_summary;
			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];
		}
	} 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 - Property

#pragma mark - Private

- (void)updateTableViewCellDataArrayByReviews:(NSArray *)reviews {
	NSMutableArray *array = [NSMutableArray array];
	for (BusVendorReview *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])];
		BusVendorReview *review = data.weaklyAssociatedObject;
		cell.starRatingView.value = review.overall_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 bus!")]];
			cell.reCommendLabel.attributedText = attributed;
		} else {
			cell.reCommendLabel.attributedText = nil;
		}
		cell.detailRatingButton.hidden = NO;
		[cell.detailRatingButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
		@weakify(self, tableView)
		[cell.detailRatingButton bk_addEventHandler:^(id sender) {
			@strongify(self)
			[self tapAccessoryButton: sender withBusVendorReview: review];
		} forControlEvents: UIControlEventTouchUpInside];
		cell.postInfoLabel.text = [NSString stringWithFormat:IMLocalizedString(@"Posted by: %@ on %@ at %@ => %@"), review.full_name, review.post_time, review.departure, review.arrival];
		cell.contentLabel.text = review.content;
		cell.folding = [data.stronglyAssociatedObject boolValue];
		[cell ready];
		[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 heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArray[indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath rowHeightWithData:data];
}

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

- (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
