//
//  XTHtmlTagTd.m
//  XTads
//
//  Created by Rune Berg on 10/07/15.
//  Copyright (c) 2015 Rune Berg. All rights reserved.
//

#import "XTHtmlTag_private.h"
#import "XTHtmlTagTd.h"
#import "XTHtmlTagTr.h"
#import "XTHtmlTagTable.h"
#import "XTBaseTextHandler.h"
#import "XTTextTableBlock.h"
#import "XTDefaultColours.h"
#import "XTLogger.h"


@implementation XTHtmlTagTd

static XTLogger* logger;

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

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

+ (BOOL)standalone
{
	return NO;
}

- (void)format:(NSObject<XTOutputFormatterProtocol> *)formatter
   textHandler:(XTBaseTextHandler *)textHandler
{
	[super format:formatter textHandler:textHandler];

	NSArray *formattedElements = [formatter handleHtmlTagTdOpen];
	[textHandler receiveFormattedElements:formattedElements];
}

- (XTFormattingSpecification *)makeFormattingSpecificationFrom:(XTFormattingSpecification *)formattingSpec
{
	//TODO !!! adapt: temp hack for gilded.gam (after 3 commands) nested table hack (<td> within <td> in nesting table)
	if (formattingSpec.activeTextTableCell != nil) {
		XTFormattingSpecification *res = [XTFormattingSpecification specificationFrom:formattingSpec];
		return res;
	}
	
	formattingSpec.tableColumnIndexPlusOne +=1; // yes, must modify parent's
	XTFormattingSpecification *res = [XTFormattingSpecification specificationFrom:formattingSpec];
	//TODO !!! handle res.activeTextTable == nil
	NSInteger tableRowIndex = (res.tableRowIndexPlusOne - 1);
	NSInteger tableColumnIndex = (res.tableColumnIndexPlusOne - 1);
	XTTextTableBlock *textTableBlock = [[XTTextTableBlock alloc] initWithTable:res.activeTextTable
													  startingRow:tableRowIndex
														  rowSpan:1 //TODO !!!
												   startingColumn:tableColumnIndex
													   columnSpan:1]; //TODO !!!
	
	[res.activeTextTable addTextTableBlock:textTableBlock];
	res.activeTextTableCell = textTableBlock;
	//[textTableBlock setBorderColor:[NSColor blackColor]]; //TODO !!! temp
	//[textTableBlock setWidth:1.0 type:NSTextBlockAbsoluteValueType forLayer:NSTextBlockBorder];
		//TODO !!! right default
		//TODO !!! attr can change
	//[textTableBlock setWidth:4.0 type:NSTextBlockAbsoluteValueType forLayer:NSTextBlockPadding];
		//TODO !!! right default
		//TODO !!! attr can change
		//TODO !!! NSTextBlockMargin?
	[textTableBlock setVerticalAlignment:NSTextBlockMiddleAlignment];
		//TODO !!! attr can change
	
	NSString *backgroundColorAttr = [self attributeAsString:@"bgcolor"];
	if (backgroundColorAttr != nil) {
		XTHtmlColor *htmlColor = [XTHtmlColor forAttributeValue:backgroundColorAttr];
		res.textTableCellHtmlColor = htmlColor;
	}

	if (res.textTableCellHtmlColor.color != nil) {
		[textTableBlock setBackgroundHtmlColor:res.textTableCellHtmlColor];
	} else if (res.textTableRowHtmlColor != nil) {
		[textTableBlock setBackgroundHtmlColor:res.textTableRowHtmlColor];
	}

	NSNumber *widthAsPercentage = [self attributeAsPercentage:@"width"];
	if (widthAsPercentage != nil) {
		[textTableBlock setWidthAsPercentage:widthAsPercentage];
	} else {
		NSNumber *widthAsPoints = [self attributeAsNumberWithOptionalSuffix:@"width"];
		if (widthAsPoints != nil) {
			[textTableBlock setWidthAsPoints:widthAsPoints];
		}
	}

	XTHtmlTagTable *parentTable = [self findParentTagTable];
	if (parentTable != nil) {
		NSNumber *tableId = parentTable.tableId;
		textTableBlock.tableId = tableId;
		
		if (parentTable.tableBorderSize >= 1) {
			NSInteger borderSize = 1;
				//TODO !!! tr/td's attr can override:
			[textTableBlock setBorderColor:[NSColor blackColor]];
			[textTableBlock setWidth:borderSize type:NSTextBlockAbsoluteValueType forLayer:NSTextBlockBorder];
			//textTableBlock.collapsesBorders = YES; //TODO !!! ? find equiv.
		}
		
		//TODO !!! tr/td's attr might override:
		NSInteger padding = parentTable.cellPadding;
		if (padding >= 1) {
			[textTableBlock setWidth:padding type:NSTextBlockAbsoluteValueType forLayer:NSTextBlockPadding];
		}

		//TODO !!! attr override?
		NSColor *cellBorderColorLeftAndTop = [XTDefaultColours tableCellBorderColorLeftAndTop];
		NSColor *cellBorderColorRightAndBottom = [XTDefaultColours tableCellBorderColorRightAndBottom];
		[textTableBlock setBorderColor:cellBorderColorLeftAndTop forEdge:NSMinXEdge];
		[textTableBlock setBorderColor:cellBorderColorLeftAndTop forEdge:NSMinYEdge];
		[textTableBlock setBorderColor:cellBorderColorRightAndBottom forEdge:NSMaxXEdge];
		[textTableBlock setBorderColor:cellBorderColorRightAndBottom forEdge:NSMaxYEdge];

		[textTableBlock recalcCellMargins];
		
	} else {
		XT_DEF_SELNAME;
		XT_WARN_0(@"parentTable == nil");
	}

	// "default is left alignment for <td> and center alignment for <th> although you can override this with an ALIGN attribute on the TR element." (HTML 3.2 spec)
	XTTextAlignMode defaultTextAlignMode = res.textAlignMode; // from parent tag (TR)
	if (defaultTextAlignMode == XT_TEXT_ALIGN_UNSPECIFIED) {
		defaultTextAlignMode = [self getDefaultTextAlignMode];
	}
	res.textAlignMode = [self getTextAlignModeWithDefault:defaultTextAlignMode];
		
	return res;
}

- (XTTextAlignMode)getDefaultTextAlignMode
{
	return XT_TEXT_ALIGN_LEFT;
}

- (XTHtmlTagTable *)findParentTagTable
{
	//TODO !!! refine: must handle misformed html, but not surrounding <table>
	XTHtmlTagTable *res = nil;
	XTHtmlTagContainer *container = [self getContainer];
	if ([container isKindOfClass:[XTHtmlTagTr class]]) {
		XTHtmlTagTr *container2 = (XTHtmlTagTr *)[container getContainer];
		if ([container2 isKindOfClass:[XTHtmlTagTable class]]) {
			res = (XTHtmlTagTable *)container2;
		}
	}
	return res;
}


- (XTHtmlTagContainer *)findCorrectContainer:(XTHtmlTagContainer *)defaultContainer
{
	XTHtmlTagContainer *res = defaultContainer;
	
	for (XTHtmlTagContainer *container = defaultContainer;
		 container != nil;
		 container = container.container) {
		
		if ([container isKindOfClass:[XTHtmlTagTr class]]) {
			// Our nearest <tr> is the one
			res = container;
			break;
		} else if ([container isKindOfClass:[XTHtmlTagTable class]]) {
			// Don't look outside nearest <table>
			break;
		}
	}

	return res;
}

- (void)formatExit:(NSObject<XTOutputFormatterProtocol> *)formatter
	   textHandler:(XTBaseTextHandler *)textHandler
{
	//TODO !!! very unfinished
	NSArray *formattedElements = [formatter handleHtmlTagTdClose:self];
	[textHandler receiveFormattedElements:formattedElements];
	
	[super formatExit:formatter textHandler:textHandler];
	
	XTHtmlTagTable *parentTagTable = [self findParentTagTable];
	XTTextTable *textTable = parentTagTable.textTable;
	[textTable recalcCellMargins];	
}

@end
