//
//  XTTextFieldWithLink.m
//  XTads
//
//  Created by Rune Berg on 06/11/15.
//  Copyright © 2015 Rune Berg. All rights reserved.
//

#import "XTTextFieldWithLink.h"
#import "XTLogger.h"


@interface XTTextFieldWithLink ()

@property BOOL hasLink;

@end


@implementation XTTextFieldWithLink

static XTLogger* logger;

+ (void)initialize
{
	logger = [XTLogger loggerForClass:[XTTextFieldWithLink class]];
}

- (void)awakeFromNib
{
	// Ensure we receive mouse events, so that we can change the mouse pointer:
	NSTrackingAreaOptions option = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
	NSTrackingArea * area = [[NSTrackingArea alloc] initWithRect:self.bounds options:option owner:self userInfo:nil];
	[self addTrackingArea:area];
}

- (void)resetCursorRects
{
	//XT_DEF_SELNAME;
	//XT_TRACE_1(@"%@", self.attributedStringValue.string);
	
	[super resetCursorRects];
	
	[self setPointinghandCursor];
}

- (void)mouseEntered:(NSEvent *)theEvent {

	[super mouseEntered:theEvent];

	//XT_DEF_SELNAME;
	//XT_TRACE_1(@"%@", self.attributedStringValue.string);

	[self setPointinghandCursor];
}

- (void)setPointinghandCursor
{
	if (self.hasLink) {
		NSRect rect = self.bounds;
		[self addCursorRect:rect cursor:[NSCursor pointingHandCursor]];
	}
}

- (void)setLinkText:(NSString *)linkText forUrl:(NSURL *)url
{
	// http://supporto.xyz/hyperlink-in-cocoa-3148/

	// needed, otherwise hyperlink won't accept mousedown:
	self.allowsEditingTextAttributes = YES;
	self.selectable = YES;
	
	NSDictionary *origDict = [self.attributedStringValue attributesAtIndex:0 effectiveRange:nil];
	NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:origDict];
	dict[NSLinkAttributeName] = url;
	dict[NSForegroundColorAttributeName] = [NSColor blueColor];
	dict[NSUnderlineStyleAttributeName] = [NSNumber numberWithInt:NSUnderlineStyleSingle];
	self.attributedStringValue = [[NSAttributedString alloc] initWithString:linkText attributes:dict];
	
	self.hasLink = YES;
}

@end
