//
//  TourSheetViewController.m
//  TakeTours
//
//  Created by Vae on 2019/1/18.
//

#import "TourSheetViewController.h"
#import "UIToolkit.h"
#import "Utility.h"
#import "StringUtils.h"
#import "CocoaUtils.h"
#import "Area.h"
#import "DrawUtils.h"
#import "SDK.h"
#import "DZNEmptyDataSetDefault.h"
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import <BlocksKit/BlocksKit.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import "Vars.h"


static NSInteger const kBottomViewHeight = 50;

@interface TourSheetViewController ()<UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UIView *backdropView;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, assign) BOOL isPresenting;
@property(nonatomic, assign) CGFloat tableHeight;
@property(nonatomic, strong) NSMutableArray *cellDataArray;
@property(nonatomic, strong) NSLayoutConstraint *tableViewBottomLayoutConstraint;
@property(nonatomic, strong) NSLayoutConstraint *tableViewHeightLayoutConstraint;
@end

@implementation TourSheetViewController

- (instancetype)init
{
	self = [super init];
	if (self) {
		self.modalPresentationStyle = UIModalPresentationCustom;
		self.transitioningDelegate = self;
		
	}
	return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	self.isPresenting = NO;
	
	self.view.backgroundColor = [UIColor clearColor];
	self.tableView = [[UITableView alloc] init];
	[self.view addSubview:self.backdropView];
	[self.view addSubview:self.tableView];
	
	self.tableView.bounces = NO;
	self.tableView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
	self.tableView.translatesAutoresizingMaskIntoConstraints = NO;

	
	self.tableViewHeightLayoutConstraint = [self.tableView.heightAnchor constraintEqualToConstant:self.tableHeight];
	
	[self.tableViewHeightLayoutConstraint setActive:YES];
	self.tableViewBottomLayoutConstraint =	[self.tableView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:kBottomViewHeight];
	[self.tableView autoPinEdgeToSuperviewEdge:ALEdgeLeading];
	[self.tableView autoPinEdgeToSuperviewEdge:ALEdgeTrailing];
	
	self.tableView.delegate = self;
	self.tableView.dataSource = self;
	[self buildCellData];
}

-(void)viewDidLayoutSubviews{
	if (@available(iOS 11, *)) {
		self.tableViewBottomLayoutConstraint.constant = - (self.view.safeAreaInsets.bottom + kBottomViewHeight);
	}else{
		self.tableViewBottomLayoutConstraint.constant = - (self.view.layoutMargins.bottom + kBottomViewHeight);
	}
	

}

#pragma mark - property

-(CGFloat)tableHeight{
	CGFloat maxHeight = CGRectGetHeight(self.view.bounds) /2.0;
	CGFloat tableHeight = (self.cityArray.count + 1) * 44 + 15;
	return  maxHeight - tableHeight > 0 ? tableHeight : maxHeight;
}

#pragma mark - private

-(void)buildCellData{
	NSMutableArray *celldataArray = [NSMutableArray array];
	@weakify(self)
	for (NSString *city in self.cityArray) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		Area *area = [self.cityDictionary objectForKey:city];
		data.text = area.label;
		data.textFont = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
		data.selectionStyle =  UITableViewCellSelectionStyleNone;
		[data setAccessoryViewBlock:^UIView *(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			UIButton *deleteButton = [[UIButton alloc] init];
			[deleteButton setImage:[UIImage imageNamed:@"cirledelete" ]forState:UIControlStateNormal];
			[deleteButton sizeToFit];
			[deleteButton bk_addEventHandler:^(id  _Nonnull sender) {
				[self.cityArray removeObject:city];
				if (self.updateSelectNumber) {
					self.updateSelectNumber();
				}
				if (self.cityArray.count == 0) {
					return ;
				}
				[UIView animateWithDuration:0.8 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
					CGRect frame = self.tableView.frame;
					self.tableViewHeightLayoutConstraint.constant -= 44;
					self.tableView.frame = frame;
					self.backdropView.alpha = 1;
				} completion:^(BOOL finished) {
					[self buildCellData];
					[self.view layoutIfNeeded];
				}];
				
			} forControlEvents:UIControlEventTouchUpInside];
			return deleteButton;
		}];

		[celldataArray addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.reuseHeight = 15;
		[celldataArray addObject:data];
	}
	self.cellDataArray = [NSMutableArray arrayWithArray:celldataArray];
	[self.tableView reloadData];
}

-(UIView *)backdropView{
	if (!_backdropView) {
		_backdropView = [[UIView alloc] initWithFrame:self.view.bounds];
		_backdropView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
		UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
		_backdropView.userInteractionEnabled = YES;
		[_backdropView addGestureRecognizer:tap];
	}
	return _backdropView;
}

-(void)handleTap{
	[self dismissViewControllerAnimated:YES completion:nil];
}

-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
	return self;
}


-(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
	return self;
}

-(NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
	return 1;
}

-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
	UIView *containerView = transitionContext.containerView;
	UIViewController *toViewcontroller = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
	if (!toViewcontroller) {
		return;
	}
	self.isPresenting = !self.isPresenting;
	
	if (self.isPresenting) {
		[containerView addSubview:toViewcontroller.view];
		
		self.backdropView.alpha = 0;
		CGRect frame = self.tableView.frame;
		frame.origin.y += self.tableHeight;
		self.tableView.frame = frame;
		
		[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
			CGRect frame = self.tableView.frame;
			frame.origin.y -= self.tableHeight;
			self.tableView.frame = frame;
			self.backdropView.alpha = 1;
		} completion:^(BOOL finished) {
			[transitionContext completeTransition:YES];
		}];
		
	}else{
		[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
			CGRect frame = self.tableView.frame;
			frame.origin.y += self.tableHeight;
			self.tableView.frame = frame;
			self.backdropView.alpha = 0;
		} completion:^(BOOL finished) {
			[transitionContext completeTransition:YES];
		}];
		
	}
}

#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];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
	UIView *headerview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44)];
	headerview.backgroundColor = [UIColor whiteColor];
	UILabel *titleLabel = [[UILabel alloc]init];
	titleLabel.text = self.isDestinations ? IMLocalizedString(@"Selected Destination(s)") :IMLocalizedString(@"Selected Departure");
	[headerview addSubview:titleLabel];
	titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
	[titleLabel autoSetDimension:ALDimensionWidth toSize:200];
	[titleLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:15];
	[titleLabel autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
	
	UIButton *deleteButton = [[UIButton alloc]init];
	[headerview addSubview:deleteButton];
	[deleteButton autoSetDimension:ALDimensionWidth toSize:20];
	[deleteButton autoSetDimension:ALDimensionHeight toSize:20];
	[deleteButton autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:15];
	[deleteButton autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
	[deleteButton  setImage:[UIImage imageNamed:@"deletes" ]forState:UIControlStateNormal];
	[deleteButton sizeToFit];
	[deleteButton bk_addEventHandler:^(id  _Nonnull sender) {
		[self.cityArray removeAllObjects];
		if (self.updateSelectNumber) {
			self.updateSelectNumber();
		}
	} forControlEvents:UIControlEventTouchUpInside];
	[DrawUtils addRoundedBorderToRect:headerview byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadius:10];
	return headerview;
}


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

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


@end

