//
//  UILabel+AutoSize.m
//
//

#import "UILabel+AutoSize.h"

@implementation UILabel (BPExtensions)

- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth {
	CGSize size;
	
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
		size = [self.text boundingRectWithSize:CGSizeMake(fixedWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: self.font } context:0].size;
	}
	else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
		size = [self.text sizeWithFont:self.font
					 constrainedToSize:CGSizeMake(fixedWidth, MAXFLOAT)
						 lineBreakMode:NSLineBreakByWordWrapping];
#pragma clang diagnostic pop
	}
	
	CGRect newFrame = self.frame;
	newFrame.size.height = ceilf(size.height);
	self.frame = newFrame;
}

- (void)sizeToFitFixedHeight:(CGFloat)fixedHeight {
	CGSize size;
	
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
		size = [self.text boundingRectWithSize:CGSizeMake(MAXFLOAT, fixedHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: self.font } context:0].size;
	}
	else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
		size = [self.text sizeWithFont:self.font
					 constrainedToSize:CGSizeMake(MAXFLOAT, fixedHeight)
						 lineBreakMode:NSLineBreakByWordWrapping];
#pragma clang diagnostic pop
	}
	
	CGRect newFrame = self.frame;
	newFrame.size.width = ceilf(size.width);
	self.frame = newFrame;
}

- (void)sizeToFitWidth {
	[self sizeToFitFixedWidth:self.frame.size.width];
}

- (void)sizeToFitHeight {
	[self sizeToFitFixedHeight:self.frame.size.height];
}

- (void)resizeForLayout {
	[self sizeToFitWidth];
}

@end


@implementation AutoSizeLabel

- (void)setText:(NSString *)text {
	[super setText:text];
	if (self.autoFitHeight)
		[self sizeToFitWidth];
	if (self.autoFitWidth)
		[self sizeToFitHeight];
}

@end
