//
//  XTTagContainerStack.m
//  XTads
//
//  Created by Rune Berg on 18/05/2018.
//  Copyright © 2018 Rune Berg. All rights reserved.
//

#import "XTTagContainerStack.h"
#import "XTHtmlTagContainer.h"
#import "XTHtmlTagOutermost.h"
#import "XTHtmlTagBanner.h"
#import "XTHtmlTagListContainer.h"
#import "XTHtmlTagLi.h"
#import "XTLogger.h"
#import "XTAllocDeallocCounter.h"


@interface XTTagContainerStack ()

@property NSMutableArray<XTHtmlTagContainer *> *array;

@end


@implementation XTTagContainerStack

static XTLogger* logger;

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

OVERRIDE_ALLOC_FOR_COUNTER
OVERRIDE_DEALLOC_FOR_COUNTER

- (instancetype)init
{
	self = [super init];
	if (self) {
		_array = [NSMutableArray arrayWithCapacity:50];
		[_array addObject:[XTHtmlTagOutermost new]];
	}
	return self;
}

- (void)reset
{
	self.array = [NSMutableArray arrayWithCapacity:50];
	[self.array addObject:[XTHtmlTagOutermost new]];
}

- (void)resetForNextCommand
{
	// Certain tags should not span game commands:
	for (NSInteger idx = self.array.count - 1; idx >= 0; idx--) {
		XTHtmlTagContainer *tagContainer = self.array[idx];
		if ([tagContainer isKindOfClass:[XTHtmlTagListContainer class]] || [tagContainer isKindOfClass:[XTHtmlTagLi class]]) {
			[self.array removeObjectAtIndex:idx];
		}
	}
}

- (void)push:(XTHtmlTagContainer *)tag
{
	[_array addObject:tag];
}

- (XTHtmlTagContainer *)pop
{
	// Guard outermost element, which is a pseudo-tag that should never be popped
	if (! [self canPop]) {
		XT_DEF_SELNAME;
		XT_ERROR_0(@"trying to pop outermost element - ignoring");
		return nil;
	}

	XTHtmlTagContainer *res = [self.array lastObject];

	[self.array removeLastObject];

	return res;
}

- (BOOL)canPop
{
	BOOL res = (self.depth >= 2);
	return res;
}

- (NSUInteger)depth
{
	return self.array.count;
}

- (XTHtmlTagContainer *)top
{
	return self.array.lastObject;
}

- (XTHtmlTagContainer *)bottom
{
	return self.array.firstObject;
}

- (void)popUntil:(XTHtmlTagContainer *)tagContainer
{
	BOOL popped = NO;

	for (NSInteger idx = self.array.count - 1; idx >= 0; idx--) {
		XTHtmlTagContainer *top = self.array[idx];
		if (top != tagContainer) {
			[self pop];
			top.closed = YES;
			popped = YES;
		} else {
			break;
		}
	}
	
	if (! popped) {
		XT_DEF_SELNAME;
		XT_ERROR_0(@"did not find tagContainer in array");
	}
}

@end
