//
// JVBottomFloatLabeledTextField.m
// Project
//
// Created by haibara on 12/11/16.
//
//

#import "JVBottomFloatLabeledTextField.h"

@interface JVFloatLabeledTextField ()
- (CGFloat)maxTopInset;
- (void)setLabelOriginForTextAlignment;
- (CGRect)insetRectForBounds:(CGRect)rect;
@end

@implementation JVBottomFloatLabeledTextField

- (CGRect)clearButtonRectForBounds:(CGRect)bounds {
	CGRect rect = [super clearButtonRectForBounds:bounds];
	rect.origin.y -= CGRectGetHeight(self.floatingLabel.frame);
	return rect;
}

- (CGRect)leftViewRectForBounds:(CGRect)bounds {
	CGRect rect = [super leftViewRectForBounds:bounds];
	rect.origin.y -= CGRectGetHeight(self.floatingLabel.frame);
	return rect;
}

- (CGRect)rightViewRectForBounds:(CGRect)bounds {
	CGRect rect = [super rightViewRectForBounds:bounds];
	rect.origin.y -= CGRectGetHeight(self.floatingLabel.frame);
	return rect;
}

- (CGFloat)maxTopInset {
	return CGFLOAT_MAX;
}

- (void)setLabelOriginForTextAlignment {
	[super setLabelOriginForTextAlignment];
	CGRect rect = self.floatingLabel.frame;
	rect.origin.y = ceil(self.font.lineHeight);
	self.floatingLabel.frame = rect;
}

- (CGRect)insetRectForBounds:(CGRect)bounds {
	CGRect rect = [super insetRectForBounds:bounds];
	rect.origin.y -= CGRectGetHeight(self.floatingLabel.frame);
	return rect;
}

- (void)showFloatingLabel:(BOOL)animated {
	void (^showBlock)(void) = ^{
		self.floatingLabel.alpha = 1;
		CGRect rect = self.floatingLabel.frame;
		rect.origin.y = ceil(self.font.lineHeight);
		self.floatingLabel.frame = rect;
	};
	if (animated || 0 != self.animateEvenIfNotFirstResponder) {
		[UIView animateWithDuration:self.floatingLabelShowAnimationDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseOut animations:showBlock completion:nil];
	} else {
		showBlock();
	}
}

- (void)hideFloatingLabel:(BOOL)animated {
	void (^hideBlock)(void) = ^{
		self.floatingLabel.alpha = 0;
		CGRect rect = self.floatingLabel.frame;
		rect.origin.y = ceil(self.font.lineHeight) - CGRectGetHeight(self.floatingLabel.frame);
		self.floatingLabel.frame = rect;
	};
	if (animated || 0 != self.animateEvenIfNotFirstResponder) {
		[UIView animateWithDuration:self.floatingLabelHideAnimationDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseIn animations:hideBlock completion:nil];
	} else {
		hideBlock();
	}
}

@end
