//
//  XTOutputTextParserBase.m
//  XTads
//
//  Created by Rune Berg on 10/07/2018.
//  Copyright © 2018 Rune Berg. All rights reserved.
//

#import "XTOutputTextParserBase.h"
#import "XTOutputTextParserBase_private.h"
#import "XTHtmlTagOutermost.h"
#import "XTHtmlTagSecondOutermost.h"
#import "XTLogger.h"


@implementation XTOutputTextParserBase

static XTLogger* logger;

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

- (id)init
{
	self = [super init];
	if (self) {
		_containerStack = [XTTagContainerStack new];
	}
	return self;
}

- (void)ensureWeHaveSecondOutermostContainer
{
	if ([self.containerStack.top isKindOfClass:[XTHtmlTagOutermost class]]) {
		//XT_DEF_SELNAME;
		XTHtmlTagOutermost *tagOutermost = (XTHtmlTagOutermost *)self.containerStack.top;
		if ([tagOutermost hasContents]) {
			XT_DEF_SELNAME;
			XT_ERROR_0(@"[tagOutermost hasContents] == YES");
		}
		XTHtmlTagSecondOutermost *secondOutermostTag = [XTHtmlTagSecondOutermost new];
		secondOutermostTag.closed = YES; //TODO !!! mv into class itself
		[tagOutermost appendToContents:secondOutermostTag];
		[secondOutermostTag assertHasContainer];
		[self pushContainer:secondOutermostTag];
		//XT_WARN_0(@"added new XTHtmlTagSecondOutermost");
	}
}

- (void)pushContainer:(XTHtmlTagContainer *)container
{
	[self.containerStack push:container];
}

- (void)appendTagToCurrentContainer:(XTHtmlTag *)tag
{
	[self ensureWeHaveSecondOutermostContainer];
	
	/*
	 	Patch certain cases of missing end tags (</...>)
	 */
	XTHtmlTagContainer *defaultContainer = self.containerStack.top;
	XTHtmlTagContainer *correctContainer = [tag findCorrectContainer:defaultContainer];
	if (correctContainer != defaultContainer) {
		[self.containerStack popUntil:correctContainer];
		defaultContainer.closed = YES;
	}
	
	[self.containerStack.top appendToContents:tag];
}

@end
