//
//  RangeCalendarViewController.m
//  Project
//
//  Created by Vae on 2018/9/17.
//

#import "RangeCalendarViewController.h"
#import "RangeCalendarCell.h"
#import "Lang.h"
#import "Vars.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "CalendarHeaderView.h"
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import <BlocksKit/UIControl+BlocksKit.h>
#import "UniversalViewWrapper.h"
#import "CocoaUtils.h"
#import "Utility.h"

static NSInteger const kPriceCellHeight = 70;
static NSInteger const kNormalCellHeight = 44;
static NSInteger const kCellMargin = 10;

@interface FSCalendar ()
@property (strong, nonatomic) NSCalendar *gregorian;
@end

@interface RangeCalendarViewController ()<FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance>
@property (weak, nonatomic) IBOutlet UniversalViewWrapper <CalendarHeaderView *>*headerViewWrapper;
@property (weak, nonatomic) IBOutlet FSCalendar *calendar;
@property (nonatomic, strong, readonly) CalendarHeaderView *headerView;
@property (nonatomic, strong) UIButton *doneButton;
@property (nonatomic, assign) BOOL isShowDepaturePrice;
@property (nonatomic, strong) NSDate *startDate;
@property (nonatomic, strong) NSDate *endDate;
@property (nonatomic, strong) NSDate *selectedDate;
@property (nonatomic, copy) void (^didCancelBlock) (void);
@property (nonatomic, copy) void (^didDoneRangeBlock) (NSDate *startDate, NSDate *endDate);
@property (nonatomic, copy) void (^didDoneBlock)(NSDate *date);
@end

@implementation RangeCalendarViewController

- (instancetype)init {
	self = [super init];
	if (self) {
		self.edgesForExtendedLayout = UIRectEdgeNone;
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	
	@weakify(self)
	if (self.didCancelBlock) {
		self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] im_initWithBarButtonSystemItem:UIBarButtonSystemItemCancel handler:^(UIBarButtonItem *barButtonItem) {
			@strongify(self)
			self.didCancelBlock();
		}];
	}
	
	[self configureRangeSelectionCalendar:self.calendar];
	self.doneButton = [[UIButton alloc] init];
	[self.doneButton setTitle:IMLocalizedString(@"Done") forState:UIControlStateNormal];
	if ([Vars is_bus_site]) {
		[self.doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[self.doneButton setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.6] forState:UIControlStateDisabled];

	}else{
		[self.doneButton setTitleColor:[Vars defaultTintColor] forState:UIControlStateNormal];
		[self.doneButton setTitleColor:[[Vars defaultTintColor] colorWithAlphaComponent:0.6] forState:UIControlStateDisabled];
	}
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.doneButton];
	[self.doneButton addTarget:self action:@selector(finish) forControlEvents:UIControlEventTouchUpInside];
	[self setupHeaderView];
}


-(void)viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];

	if (self.isRoundTrip) {
		if (self.startDate && self.endDate) {
			[self.calendar setValue:[NSMutableArray arrayWithArray:@[self.startDate,self.endDate]] forKey:@"selectedDates"];
			[self.calendar selectDate:self.startDate scrollToDate:YES];
		}
	}else{
		[self.calendar selectDate:self.selectedDate scrollToDate:YES];
	}
	[self.calendar reloadData];	
}

#pragma mark - load view

-(void)setupHeaderView{
	@weakify(self)
	self.headerViewWrapper.viewNibName = NSStringFromClass([CalendarHeaderView class]);
	if (!self.isHeaderViewUserInteractionEnabled) {
		self.headerView.cancleButton.hidden = YES;
	}
	self.headerView.userInteractionEnabled = self.isHeaderViewUserInteractionEnabled;
	self.isShowDepaturePrice = YES;
	[self changeHeaderViewText];
	
	if (!self.isRoundTrip) {
		self.headerView.cancleButton.hidden = YES;
	}
	
	if (self.isHotel) {
		self.headerView.checkInLabel.hidden = NO;
		self.headerView.CheckOutLabel.hidden = NO;
		if ([Vars is_tours_site]) {
			self.headerView.checkInLabel.text = IMLocalizedString(@"Check-in date");
			self.headerView.CheckOutLabel.text = IMLocalizedString(@"Check-out date");
		}
	}
	
	self.headerView.selectRightView = ^{
		@strongify(self)
		self.isShowDepaturePrice = NO;
		self.headerView.cancleButton.hidden = NO;
		if (!self.isRoundTrip) {
			self.isRoundTrip = YES;
			self.startDate = self.selectedDate;
			self.endDate = [DateUtils addDays:self.startDate amount:1];
		}
		if (self.startDate && self.endDate) {
			[self.calendar setValue:[NSMutableArray arrayWithArray:@[self.startDate,self.endDate]] forKey:@"selectedDates"];
		}
		[self.calendar reloadData];
		[self changeHeaderViewText];
	};
	
	self.headerView.selectLeftView = ^{
		@strongify(self)
		self.isShowDepaturePrice = YES;
		[self.calendar reloadData];
		[self changeHeaderViewText];
	};
	self.headerView.close = ^{
		@strongify(self)
		self.doneButton.enabled = YES;
		self.headerView.cancleButton.hidden = YES;
		self.isRoundTrip = NO;
		self.isShowDepaturePrice = YES;
		[self.calendar selectDate:self.startDate];
		if (self.endDate && ![self.startDate isEqualToDate:self.endDate]) {
			[self.calendar deselectDate:self.endDate];
			self.endDate = nil;
		}
		self.selectedDate = self.startDate;
		[self changeHeaderViewText];
		[self.calendar reloadData];
	};
	if (self.isRoundTrip) {
		[self.headerView tapRightView];
	}
	
}

#pragma mark - protery

-(CalendarHeaderView *)headerView{
	return [self.headerViewWrapper get];
}

#pragma mark - Action

-(void)changeHeaderViewText{
	self.headerView.depatureDateLabel.text = [[Utility RANGECALENDAR_DATE_FORMAT] format:self.startDate];
	self.headerView.returnDateLabel.text = [[Utility RANGECALENDAR_DATE_FORMAT] format:self.endDate];
	NSString *startDateStr = [[DateFormatUtils ISO_DATE_FORMAT]  format:self.startDate];
	NSString *endDateStr = [[DateFormatUtils ISO_DATE_FORMAT]  format:self.endDate];
	NSString *selectDateStr = [[DateFormatUtils ISO_DATE_FORMAT] format:self.selectedDate];
	NSString *startDatePrice = self.calendarPrice.depaturePriceDictionary[startDateStr];
	NSString *endDatePrice = self.calendarPrice.returnPriceDictionary[endDateStr];
	NSString *selectDatePrice = self.calendarPrice.depaturePriceDictionary[selectDateStr];
	self.headerView.returnPriceLabel.font = [UIFont systemFontOfSize:14];
	if (self.isRoundTrip ) {
		if (!self.isHotel) {
			self.title = @"Departure & Return";
		}
		self.headerView.depaturePriceLabel.text = startDatePrice ? [NSString stringWithFormat:@"$%@", startDatePrice] : @"";
		self.headerView.returnPriceLabel.text = endDatePrice ?[NSString stringWithFormat:@"$%@", endDatePrice] : @"";
		if (!endDateStr ) {
			self.headerView.returnDateLabel.text = @"Return";
			self.headerView.returnPriceLabel.text = @"Book round trip into save extra";
			self.headerView.returnPriceLabel.font = [UIFont systemFontOfSize:12];
		}
	}else{
		self.title = IMLocalizedString(@"Departure Date");
		self.headerView.returnDateLabel.text = @"Return";
		self.headerView.returnPriceLabel.text = @"(Optional)";
		self.headerView.depatureDateLabel.text = [[Utility RANGECALENDAR_DATE_FORMAT] format:self.selectedDate];
		self.headerView.depaturePriceLabel.text = selectDatePrice ? [NSString stringWithFormat:@"$%@", selectDatePrice]: @"";
	}
	
	if (!self.isShowPriceTitle) {
		self.headerView.depaturePriceLabel.text = @"";
		self.headerView.returnPriceLabel.text = @"";
	}
	
	if (self.isBusHotel) {
		self.headerView.cancleButton.hidden = YES;
	}
	
	if (self.isHotel ) {
		self.headerView.cancleButton.hidden = YES;
		if (!endDateStr) {
			self.headerView.returnDateLabel.text = @"";
		}
	}
}

-(void)finish{
	if (self.isRoundTrip) {
		if (!self.endDate && self.startDate) {
			self.endDate = self.startDate;
		}
		self.didDoneRangeBlock(self.startDate, self.endDate);
	}else{
		self.didDoneBlock(self.selectedDate);
	}
}

#pragma mark - FSCalendarDataSource
- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar{
	return [DateUtils truncate:self.minimumDate unit:NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay];
}

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar{
	return [DateUtils truncate:self.maximumDate unit:NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay];
}

-(FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)position{
	RangeCalendarCell *cell = [calendar dequeueReusableCellWithIdentifier:NSStringFromClass([RangeCalendarCell class]) forDate:date atMonthPosition:position];
	[self configureCell:cell forDate:date atMonthPosition:position onCalendar:calendar];
	if (self.isShowPriceTitle) {
		cell.titleHeight = kPriceCellHeight - kCellMargin;
	}else{
		cell.titleHeight = kNormalCellHeight - kCellMargin;
	}
	return cell;
}

- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
	NSString *dateStr = [[DateFormatUtils ISO_DATE_FORMAT]  format:date];
	if (self.isShowPriceTitle) {
		if (self.isShowDepaturePrice) {
			if ([self.calendarPrice.depaturePriceDictionary valueForKey:dateStr]) {
				return [NSString stringWithFormat:@"$%@", self.calendarPrice.depaturePriceDictionary[dateStr]];
			}
		}else{
			if ([self.calendarPrice.returnPriceDictionary valueForKey:dateStr]) {
				return [NSString stringWithFormat:@"$%@", self.calendarPrice.returnPriceDictionary[dateStr]];
			}
		}
	}
	return @"";
}

- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance subtitleDefaultColorForDate:(NSDate *)date{
	NSString *dateStr = [[DateFormatUtils ISO_DATE_FORMAT]  format:date];
	BOOL isLowestPrice = NO;
	if (self.isShowDepaturePrice) {
		NSString* pricetext = self.calendarPrice.depaturePriceDictionary[dateStr];
		if ([pricetext isEqualToString:self.calendarPrice.depatureLowestPrice]) {
			isLowestPrice = YES;
		}
	}else{
		NSString* pricetext = self.calendarPrice.returnPriceDictionary[dateStr];
		if ([pricetext isEqualToString:self.calendarPrice.returnLowestPrice]) {
			isLowestPrice = YES;
		}
	}
	if (isLowestPrice) {
		return [Utility lowestPriceColor];
	}
	return  [Utility defaultSubTitleColor];
}

#pragma mark - FSCalendarDelegate
- (BOOL)calendar:(FSCalendar *)calendar shouldDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
	if ([date isEqualToDate:self.startDate] || [date isEqualToDate:self.endDate]) {
		if (!self.endDate) {
			if (self.isHotel || self.isBusHotel) {
				self.doneButton.enabled = NO;
			}else{
				self.doneButton.enabled = YES;
				self.endDate = self.startDate;
				[self.headerView tapRightView];
			}
		}else if (self.startDate && self.endDate) {
			self.doneButton.enabled = NO;
			[calendar deselectDate:self.startDate];
			[calendar deselectDate:self.endDate];
			self.startDate = date;
			[self.calendar selectDate:self.startDate];
			self.endDate = nil;
			[self.headerView tapLeftView];
		}
		[self configureVisibleCellsOnCalendar:calendar];
	}
	return NO;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
	if (self.isRoundTrip) {
		if (self.endDate) {
			[calendar deselectDate:self.startDate];
			[calendar deselectDate:self.endDate];
			self.startDate = date;
			self.endDate = nil;
			self.doneButton.enabled = NO;
			[self.headerView tapLeftView];
		} else if (!self.startDate) {
			self.doneButton.enabled = NO;
			self.startDate = date;
			[self changeHeaderViewText];
			return;
		} else {
			if ([[date earlierDate:self.startDate] isEqualToDate:date]) {
				[calendar deselectDate:self.startDate];
				self.startDate = date;
				self.endDate = nil;
				self.doneButton.enabled = NO;
				[self.headerView tapLeftView];
			}else{
				self.doneButton.enabled = YES;
				self.endDate = date;
				[self.headerView tapRightView];
				return;
			}
		}
	}else{
		self.startDate = nil;
		self.endDate = nil;
		[self.calendar deselectDate:self.selectedDate];
		[self.calendar selectDate:date];
		self.selectedDate = date;
		[self changeHeaderViewText];
	}
	[self.calendar selectDate:date scrollToDate:YES];
	[self configureVisibleCellsOnCalendar:calendar];
}

#pragma mark - Public
- (void)selectRangeFromStartDate:(NSDate *)startDate toEndDate:(NSDate *)endDate {
	self.startDate = startDate;
	self.endDate = endDate;
}

-(void)selectDate:(NSDate *)date{
	self.selectedDate = date;
}

#pragma mark - Private

- (void)configureRangeSelectionCalendar:(FSCalendar *)calendar {
	calendar.backgroundColor = [UIColor whiteColor];
	calendar.locale = [CocoaUtils applicationLocale];
	calendar.dataSource = self;
	calendar.delegate = self;
	calendar.pagingEnabled = NO;
	calendar.allowsMultipleSelection = YES;
	calendar.appearance.weekdayTextColor = [Utility defaultSubTitleColor];
	calendar.appearance.headerTitleColor = [Utility defaultSubTitleColor];
	calendar.appearance.titleDefaultColor =[Utility defaultTitleColor];
	calendar.appearance.titleSelectionColor = [UIColor whiteColor];
	calendar.appearance.subtitleSelectionColor = [UIColor whiteColor];
	calendar.appearance.titleFont = [UIFont systemFontOfSize:17];
	calendar.appearance.subtitleFont = [UIFont systemFontOfSize:12];
	calendar.appearance.weekdayFont = [UIFont systemFontOfSize:12];
	calendar.appearance.headerTitleFont = [UIFont systemFontOfSize:15];
	calendar.appearance.subtitleOffset = CGPointMake(0, kCellMargin);
	calendar.swipeToChooseGesture.enabled = YES;
	calendar.placeholderType = FSCalendarPlaceholderTypeNone;
	calendar.today = nil;
	if (self.isShowPriceTitle) {
		calendar.rowHeight = kPriceCellHeight;
	}else{
		calendar.rowHeight = kNormalCellHeight;
		calendar.appearance.titleOffset = CGPointMake(0, 5);
	}
	[self.calendar registerClass:[RangeCalendarCell class] forCellReuseIdentifier:NSStringFromClass([RangeCalendarCell class])];
}


- (void)configureVisibleCellsOnCalendar:(FSCalendar *)calendar {
	[calendar.visibleCells enumerateObjectsUsingBlock:^(__kindof FSCalendarCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
		NSDate *date = [calendar dateForCell:obj];
		FSCalendarMonthPosition position = [calendar monthPositionForCell:obj];
		[self configureCell:obj forDate:date atMonthPosition:position onCalendar:calendar];
	}];
}


- (void)configureCell:(RangeCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition onCalendar:(FSCalendar *)calendar {
	//One way
	if (!self.isRoundTrip) {
		NSDate *selectedDate = self.calendar.selectedDate;
		if (selectedDate && [calendar.gregorian isDate:date inSameDayAsDate:selectedDate]) {
			cell.selectionLayer.hidden = NO;
			cell.middleLayer.hidden = YES;
			cell.selectionType = SelectionTypeSingle;
			[cell setNeedsLayout];
			return;
		}
	}
	
	//round trip
	if (self.startDate && self.endDate) {
		BOOL isSelect = NO;
		BOOL isMiddle = [date compare:self.startDate] != [date compare:self.endDate];
		cell.middleLayer.hidden = !isMiddle;
		//中间选择的日期
		if (isMiddle) {
			isSelect = YES;
			cell.selectionType = SelectionTypeMiddle;
		}
		//开始结束日期
		if ([calendar.gregorian isDate:date inSameDayAsDate:self.startDate] || [calendar.gregorian isDate:date inSameDayAsDate:self.endDate]) {
			isSelect = YES;
			cell.selectionType = SelectionTypeBorder;
		}
		//未选择日期
		if (!isSelect) {
			cell.selectionType = SelectionTypeNone;
		}
		//单个选择日期
	}else if (self.startDate && [calendar.gregorian isDate:date inSameDayAsDate:self.startDate] && !self.endDate) {
		cell.selectionType = SelectionTypeStart;
	}else{
		//未选择日期
		cell.selectionType = SelectionTypeNone;
	}
	cell.isHotel = self.isHotel;
	[cell setNeedsLayout];
}

@end
