//
//  XTTextTable.m
//  XTads
//
//  Created by Rune Berg on 03/09/2018.
//  Copyright © 2018 Rune Berg. All rights reserved.
//

#import "XTTextTable.h"
#import "XTLogger.h"
#import "XTTextAlignMode.h"
#import "XTOutputFormatter.h"
#import "XTTableColumnWidthTracker.h"
#import "XTAllocDeallocCounter.h"


@implementation XTTextTable

static XTLogger* logger;

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

OVERRIDE_ALLOC_FOR_COUNTER
OVERRIDE_DEALLOC_FOR_COUNTER

- (instancetype)init
{
	self = [super init];
	if (self) {
		_cellSpacing = 2;
		_textTableBlocks = [NSMutableArray arrayWithCapacity:50];
		_numberOfRows = 0;
		_widthAsPercentage = nil;
		_alignment = XT_TEXT_ALIGN_UNSPECIFIED;
	}
	return self;
}

- (void)addTextTableBlock:(XTTextTableBlock *)textTableBlock
{
	[self.textTableBlocks addObject:textTableBlock];
	
	NSInteger newNumberOfColumns = textTableBlock.startingColumn + 1;
	if (newNumberOfColumns > self.numberOfColumns) {
		self.numberOfColumns = newNumberOfColumns;
	}
	
	NSInteger newNumberOfRows = textTableBlock.startingRow + 1;
	if (newNumberOfRows > self.numberOfRows) {
		self.numberOfRows = newNumberOfRows;
	}
}

- (NSRect)rectForBlock:(NSTextTableBlock *)block
		 layoutAtPoint:(NSPoint)startingPoint
				inRect:(NSRect)rect
		 textContainer:(NSTextContainer *)textContainer
		characterRange:(NSRange)charRange
{
	//XT_DEF_SELNAME;
	//XT_WARN_2(@"row=%ld col=%ld", block.startingRow, block.startingColumn);

	NSRect res = [super rectForBlock:block layoutAtPoint:startingPoint inRect:rect textContainer:textContainer characterRange:charRange];

	return res;
}

- (NSRect)boundsRectForBlock:(NSTextTableBlock *)block
				 contentRect:(NSRect)contentRect
					  inRect:(NSRect)rect
			   textContainer:(NSTextContainer *)textContainer
			  characterRange:(NSRange)charRange
{
	//XTTextTableBlock *castBlock = (XTTextTableBlock *)block;
	//NSInteger col = block.startingColumn;
	//NSInteger row = block.startingRow;
	
	//XT_DEF_SELNAME;
	//XT_WARN_2(@"row=%ld col=%ld", block.startingRow, block.startingColumn);
	
	NSRect res = [super boundsRectForBlock:block contentRect:contentRect inRect:rect textContainer:textContainer characterRange:charRange];
	return res;
}

- (NSInteger)borderSize
{
	NSInteger res = 0;
	NSTextBlockValueType valueType = [self widthValueTypeForLayer:NSTextBlockBorder edge:NSMaxYEdge];
	if (valueType == NSTextBlockAbsoluteValueType) {
		res = [self widthForLayer:NSTextBlockBorder edge:NSMaxYEdge];
	} else {
		//TODO !!! handle pct case too?
		int brkpt = 1;
	}
	return res;
}

- (void)recalcCellMargins
{
	for (XTTextTableBlock *textTableBlock in self.textTableBlocks) {
		[textTableBlock recalcCellMargins];
	}
}

- (void)clear
{
	[self.textTableBlocks removeAllObjects];
	self.textTableBlocks = nil;
}


@end
