//
//  XTBannerTextView.m
//  XTads
//
//  Created by Rune Berg on 25/12/15.
//  Copyright © 2015 Rune Berg. All rights reserved.
//

#import "XTBannerTextView.h"
#import "XTLogger.h"
#import "XTPrefs.h"
#import "XTNotifications.h"
#import "XTAllocDeallocCounter.h"
#import "XTTabStopUtils.h"
#import "XTBannerTextHandler.h"


@class XTBannerTextHandler;


@interface XTBannerTextView ()

@property BOOL hasDoneCustomInit;

@end


//TODO refactor !!! wrt XTMainTextView
@implementation XTBannerTextView

static XTLogger* logger;

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

OVERRIDE_ALLOC_FOR_COUNTER
OVERRIDE_DEALLOC_FOR_COUNTER

- (id)initWithFrame:(NSRect)frame
{
	//XT_DEF_SELNAME;
	//XT_TRACE_0(@"");

	self = [super initWithFrame:frame];
	if (self) {
		[self customInit];
	}
	return self;
}

- (void)customInit
{
	if (_hasDoneCustomInit) {
		return;
	}
	
	[super customInit];

	[self setEditable:NO];
	
	//_showCursor = YES;
	
	_hasBorder = NO;
	
	// don't propagate our font to NSFontPanel
	[self setUsesFontPanel:NO];
	
	[self setAutomaticSpellingCorrectionEnabled:NO];
	
	[self syncWithPrefs];
	
	_hasDoneCustomInit = YES;
}

- (BOOL)recalcsTabsInLiveResize
{
	return YES;
}

- (void)syncWithPrefs
{
	BOOL spellCheck = self.prefs.spellCheckGameText.value.boolValue;
	[self setContinuousSpellCheckingEnabled:spellCheck];
	
	BOOL gramCheck = self.prefs.grammarCheckGameText.value.boolValue;
	[self setGrammarCheckingEnabled:gramCheck];

	//TODO unless set by game:
	//TODO text color
}

- (BOOL)displaysLinkToolTips
{
	return self.prefs.linksShowToolTips.value.boolValue;
}

- (void)changeFont:(id)sender
{
	// Nothing - we don't want NSFontPanel to directly change our font
}

- (void)keyDown:(NSEvent *)theEvent
{
	// Nothing - we don't want arrow keys etc. to scroll banner
	// (but allow cmd-a and cmd-c, so user can copy text)
	
	[XTNotifications notifySetFocusToMainOutputView:self];
}

- (void)unselectText
{
	[self setSelectedRange:NSMakeRange(0, 0)];
}

// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextLayout/Tasks/CountLines.html
- (NSUInteger)countRenderedTextLines
{
	NSLayoutManager *layoutManager = [self layoutManager];
	
	NSUInteger numberOfGlyphs =	[layoutManager numberOfGlyphs];
	NSUInteger numberOfLines;
	NSUInteger index;
	NSRange lineRange;
	
	for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++) {
		
		(void) [layoutManager lineFragmentRectForGlyphAtIndex:index
											   effectiveRange:&lineRange];
		index = NSMaxRange(lineRange);
	}
	
	return numberOfLines;
}

- (NSUInteger)countCharsInText
{
	NSUInteger res = [self.textStorage length];
	return res;
}

- (BOOL)shouldLogDodgyReturnFromFindYCoordOfInsertionPoint
{
	return NO; // can happen for banners
}

@end
