//
//  XTHtmlTagTable.m
//  TadsTerp
//
//  Created by Rune Berg on 24/07/14.
//  Copyright (c) 2014 Rune Berg. All rights reserved.
//

#import "XTHtmlTag_private.h"
#import "XTHtmlTagTable.h"
#import "XTHtmlTagDiv.h"
#import "XTHtmlTagCenter.h"
#import "XTHtmlUtils.h"
#import "XTBaseTextHandler.h"
#import "XTTextTable.h"
#import "XTTableColumnWidthTracker.h"
#import "XTDefaultColours.h"
#import "XTStringUtils.h"


@implementation XTHtmlTagTable

@synthesize tableId = _tableId;
@synthesize tableBorderSize = _tableBorderSize;
@synthesize cellSpacing = _cellSpacing;
@synthesize cellPadding = _cellPadding;
@synthesize textTable = _textTable;

+ (NSString *)name
{
	return @"table";
}

+ (BOOL)standalone
{
	return NO;
}

- (BOOL)blockLevel
{
	return YES;
}

- (BOOL)blockLevelSpacingBefore
{
	return NO;
}

- (BOOL)blockLevelSpacingAfter
{
	return NO;
}

- (instancetype)init
{
	self = [super init];
	if (self) {
		_tableId = [[XTTableColumnWidthTracker tracker] registerNewTable];
		_tableBorderSize = 0; // no border by default
		_cellSpacing = 2;
		_cellPadding = 1;
		_textTable = nil;
	}
	return self;
}

//TODO !!! too long - break up
- (XTFormattingSpecification *)makeFormattingSpecificationFrom:(XTFormattingSpecification *)formattingSpec
{
	XTFormattingSpecification *res = [XTFormattingSpecification specificationFrom:formattingSpec];
	
	XTTextAlignMode tableTextAlignMode = XT_TEXT_ALIGN_LEFT;
	if ([self shouldInheritHorizAlignmentFromContainer]) {
		tableTextAlignMode = res.textAlignMode;
	}

	// Don't let container's alignment bleed into cells' alignment
	res.textAlignMode = XT_TEXT_ALIGN_LEFT;

	XTTextTable *textTable = [XTTextTable new];
	_textTable = textTable;
	
	res.activeTextTable = textTable;
	
	textTable.tableId = self.tableId;
	textTable.numberOfColumns = 1;
	// textTable.collapsesBorders = YES; -- no trace of this in html tads src or html 3.2 spec
	textTable.hidesEmptyCells = NO;
	
	NSNumber *widthAsPercentageObj = [self attributeAsPercentage:@"width"];
	if (widthAsPercentageObj != nil) {
		textTable.widthAsPercentage = widthAsPercentageObj;
	}
	if (textTable.widthAsPercentage == nil) {
		NSNumber *widthAsPoints = [self attributeAsNumber:@"width"];
		if (widthAsPoints != nil) {
			textTable.widthAsPoints = widthAsPoints;
		}
	}
	
	NSNumber *borderSizeObj = [self attributeAsNumber:@"border"];
	if (borderSizeObj != nil) {
		NSInteger tempBorderSize = borderSizeObj.integerValue;
		if (tempBorderSize >= 0) {
			_tableBorderSize = tempBorderSize;
		}
		if (_tableBorderSize >= 1) {
			[textTable setWidth:_tableBorderSize type:NSTextBlockAbsoluteValueType forLayer:NSTextBlockBorder];
		}
	}

	//TODO !!! for cells too
	//TODO !!! attr override?
	NSColor *tableBorderColorLeftAndTop = [XTDefaultColours tableBorderColorLeftAndTop];
	NSColor *tableBorderColorRightAndBottom = [XTDefaultColours tableBorderColorRightAndBottom];
	[textTable setBorderColor:tableBorderColorLeftAndTop forEdge:NSMinXEdge];
	[textTable setBorderColor:tableBorderColorLeftAndTop forEdge:NSMinYEdge];
	[textTable setBorderColor:tableBorderColorRightAndBottom forEdge:NSMaxXEdge];
	[textTable setBorderColor:tableBorderColorRightAndBottom forEdge:NSMaxYEdge];

	NSNumber *cellSpacingObj = [self attributeAsNumber:@"cellspacing"];
	if (cellSpacingObj != nil) {
		NSInteger tempCellSpacing = cellSpacingObj.integerValue;
		if (tempCellSpacing >= 0) {
			_cellSpacing = tempCellSpacing;
		}
		if (_cellSpacing >= 1) {
			textTable.cellSpacing = _cellSpacing;
		}
	}

	// Ensure text before table doesn't touch table's top border
	[textTable setWidth:2.0 type:NSTextBlockAbsoluteValueType forLayer:NSTextBlockMargin edge:NSMinYEdge];
	
	NSNumber *cellPaddingObj = [self attributeAsNumber:@"cellpadding"];
	if (cellPaddingObj != nil) {
		NSInteger tempCellPadding = cellPaddingObj.integerValue;
		if (tempCellPadding >= 0) {
			_cellPadding = tempCellPadding;
		}
	}
	
	NSString *backgroundColorAttr = [self attributeAsString:@"bgcolor"];
	if (backgroundColorAttr != nil) {
		XTHtmlColor *htmlColor = [XTHtmlColor forAttributeValue:backgroundColorAttr];
		[textTable setBackgroundHtmlColor:htmlColor];
	}

	textTable.alignment = [self getTextAlignMode:tableTextAlignMode
							defaultToLeftAligned:NO];

	return res;
}

- (BOOL)shouldInheritHorizAlignmentFromContainer
{
	return [XTHtmlUtils tagIsEnclosedByDivOrCenter:self];
}

- (void)postFormatForBlockLevel:(NSObject<XTOutputFormatterProtocol> *)formatter
					textHandler:(XTBaseTextHandler *)textHandler
{
	// Nothing. Last <td> (or, when no rows/cells, <table>) will have emitted the only newline we need.
}

- (void)formatExit:(NSObject<XTOutputFormatterProtocol> *)formatter
	   textHandler:(XTBaseTextHandler *)textHandler
{
	NSArray *formattedElements = [formatter handleHtmlTagTableClose:self];
	[textHandler receiveFormattedElements:formattedElements];

	[super formatExit:formatter textHandler:textHandler];
}

@end
