//
//  Hyperlink.m
//
//

#import "Hyperlink.h"
#import "NSStringPunycodeAdditions.h"

@implementation Hyperlink {
	NSURL * _URL;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
		[self configure];
    }
    return self;
}

- (void)awakeFromNib {
	[self configure];
	[super awakeFromNib];
}

- (void)configure {
	[self addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)drawRect:(CGRect)rect
{
	if (!self.isEnabled) {
		return;
	}
	if (!self.text || self.text.length == 0) {
		return;
	}

    CGRect textRect = self.titleLabel.frame;
    CGFloat lineY = self.titleLabel.font.descender + 1;
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
	CGColorRef underlineColor = self.titleLabel.textColor.CGColor;
	underlineColor = CGColorCreateCopyWithAlpha(underlineColor, self.titleLabel.alpha);
	
    CGContextSetStrokeColorWithColor(contextRef, underlineColor);
    CGContextMoveToPoint(contextRef, textRect.origin.x, textRect.origin.y + textRect.size.height + lineY);
    CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width, textRect.origin.y + textRect.size.height + lineY);
    CGContextClosePath(contextRef);
    CGContextDrawPath(contextRef, kCGPathStroke);
	CGColorRelease(underlineColor);
}

- (void)setHighlighted:(BOOL)highlighted
{
	[super setHighlighted:highlighted];
	[self setNeedsDisplay];
}

- (void)action:(id)sender {
	[[UIApplication sharedApplication] openURL:_URL];
}

- (void)setText:(NSString *)text {
	_text = text;
	[self setTitle:text forState:UIControlStateNormal];
	[self setNeedsDisplay];
}

- (void)setURLString:(NSString *)URLString {
	_URL = [NSURL URLWithUnicodeString:URLString];
	self.enabled = [[UIApplication sharedApplication] canOpenURL:_URL];
}

- (void)setEnabled:(BOOL)enabled
{
	[super setEnabled:enabled];
	[self setNeedsDisplay];
}

@end
