//
//  XTHtmlTagCaption.m
//  XTads
//
//  Created by Rune Berg on 07/09/2021.
//  Copyright © 2021 Rune Berg. All rights reserved.
//

#import "XTHtmlTagCaption.h"
#import "XTHtmlTag_private.h"
#import "XTBaseTextHandler.h"
#import "XTHtmlTagTable.h"
#import "XTTextTableBlockCaption.h"
#import "XTTableDimensionsTracker.h"
#import "XTLogger.h"


@interface XTHtmlTagCaption ()

@property (weak)XTBaseTextHandler *textHandler;

@end


@implementation XTHtmlTagCaption

static XTLogger* logger;

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

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

+ (BOOL)standalone
{
	return NO;
}

- (void)format:(NSObject<XTOutputFormatterProtocol> *)formatter
   textHandler:(XTBaseTextHandler *)textHandler
{
	self.textHandler = textHandler;

	[super format:formatter textHandler:textHandler];

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

- (XTFormattingSpecification *)makeFormattingSpecificationFrom:(XTFormattingSpecification *)formattingSpec
{
	XTFormattingSpecification *res = [XTFormattingSpecification specificationFrom:formattingSpec];
	
	if (! [self hasValidParentTag]) {
		return res;
	}

	//TODO !!! adapt for nested tables
	if (formattingSpec.activeTextTableCell != nil) {
		return res;
	}

	res.textAlignMode = [self getTextAlignModeWithDefault:XT_TEXT_ALIGN_CENTER];

	XTTextVerticalAlignMode vertAlign = [self getCaptionVerticalAlignMode];
	NSInteger tableRowIndex;
	if (vertAlign == XT_TEXT_VERTICAL_ALIGN_BOTTOM) {
		tableRowIndex = 99999;
	} else {
		tableRowIndex = 0;
	}

	XTTextTableBlock *textTableBlock = [[XTTextTableBlockCaption alloc] initWithTable:res.activeTextTable
													  startingRow:tableRowIndex
														  rowSpan:1
												   startingColumn:0
													   columnSpan:99  // all columns
														 textView:self.textHandler.textView];
	
	[textTableBlock setInheritedHeadIndent:[res totalHeadIndent]];
	[textTableBlock setInheritedTailIndent:[res totalTailIndent]];

	XTHtmlColor *htmlColor = [XTHtmlColor forEffectiveScreenBackground];
	res.textTableCellHtmlColor = htmlColor;
	[textTableBlock setBackgroundHtmlColor:res.textTableCellHtmlColor];

	[res.activeTextTable addTextTableBlock:textTableBlock];
	res.activeTextTableCell = textTableBlock;
	
	XTHtmlTagTable *parentTable = [self findParentTagTable];
	if (parentTable != nil) {
		NSNumber *tableId = parentTable.tableId;
		textTableBlock.tableId = tableId;
	}

	return res;
}

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

- (XTTextAlignMode)getTextAlignModeWithDefault:(XTTextAlignMode)defaultTextAlignMode
{
	XT_DEF_SELNAME;
	
	XTTextAlignMode res;
	
	NSString *attrNameAlign = @"align";
	
	if (! [self hasAttribute:attrNameAlign]) {
		res = defaultTextAlignMode;
	} else if ([self hasAttribute:attrNameAlign withCaseInsensitiveValue:@"right"]) {
		res = XT_TEXT_ALIGN_RIGHT;
	} else if ([self hasAttribute:attrNameAlign withCaseInsensitiveValue:@"center"]) {
		res = XT_TEXT_ALIGN_CENTER;
	} else if ([self hasAttribute:attrNameAlign withCaseInsensitiveValue:@"left"]) {
		res = XT_TEXT_ALIGN_LEFT;
	} else if ([self hasAttribute:attrNameAlign withCaseInsensitiveValue:@"justify"]) {
		res = XT_TEXT_ALIGN_JUSTIFY;
	} else {
		if ([self hasAttribute:attrNameAlign withCaseInsensitiveValue:@"top"] ||
			[self hasAttribute:attrNameAlign withCaseInsensitiveValue:@"bottom"]) {
			// ok
		} else {
			NSString *alignAttr = [self attributeAsString:@"align"];
			XT_ERROR_1(@"unknown align attr value \"%@\"", alignAttr)
		}
		res = defaultTextAlignMode;
	}
	
	return res;
}

- (XTTextVerticalAlignMode)getCaptionVerticalAlignMode
{
	XT_DEF_SELNAME;
	
	XTTextVerticalAlignMode res = XT_TEXT_VERTICAL_ALIGN_TOP;
	
	//TODO !!! clean up:
	NSString *alignAttrName = @"align";
	/*if (! [self hasAttribute:valignAttrName]) {
		// ok
	} else*/ if ([self hasAttribute:alignAttrName withCaseInsensitiveValue:@"top"]) {
		res = XT_TEXT_VERTICAL_ALIGN_TOP;
	} else if ([self hasAttribute:alignAttrName withCaseInsensitiveValue:@"bottom"]) {
		res = XT_TEXT_VERTICAL_ALIGN_BOTTOM;
	} /*else {
		NSString *attrValue = [self attributeAsString:valignAttrName];
		XT_ERROR_1(@"unknown valign attr value \"%@\"", attrValue)
	}*/

	NSString *valignAttrName = @"valign";
	if (! [self hasAttribute:valignAttrName]) {
		// ok
	} else if ([self hasAttribute:valignAttrName withCaseInsensitiveValue:@"top"]) {
		res = XT_TEXT_VERTICAL_ALIGN_TOP;
	} else if ([self hasAttribute:valignAttrName withCaseInsensitiveValue:@"bottom"]) {
		res = XT_TEXT_VERTICAL_ALIGN_BOTTOM;
	} else {
		NSString *attrValue = [self attributeAsString:valignAttrName];
		XT_ERROR_1(@"unknown valign attr value \"%@\"", attrValue)
	}
	
	return res;
}

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

- (BOOL)hasValidParentTag
{
	XTHtmlTag *parentTag = self.container;
	BOOL res = [parentTag isKindOfClass:[XTHtmlTagTable class]];
	return res;
}

@end
