//
//  XTHtmlUtils.m
//  XTads
//
//  Created by Rune Berg on 15/03/2019.
//  Copyright © 2019 Rune Berg. All rights reserved.
//

#import "XTHtmlUtils.h"
#import "XTHtmlTag_private.h"
#import "XTHtmlTagDiv.h"
#import "XTHtmlTagCenter.h"
#import "XTHtmlTagListContainer.h"
#import "XTHtmlTagLi.h"


@implementation XTHtmlUtils

+ (BOOL)tagIsEnclosedByDivOrCenter:(XTHtmlTag *)tag
{
	BOOL res = NO;
	
	for (XTHtmlTagContainer *container = tag.container;
		 container != nil && res == NO;
		 container = container.container) {
		
		if ([container isKindOfClass:[XTHtmlTagDiv class]] || [container isKindOfClass:[XTHtmlTagCenter class]]) {
			res = YES;
		}
	}
	
	return res;
}

+ (BOOL)tagIsEnclosedByListOrListItem:(XTHtmlTag *)tag
{
	BOOL res = NO;
	
	for (XTHtmlTagContainer *container = tag.container;
		 container != nil && res == NO;
		 container = container.container) {
		
		if ([container isKindOfClass:[XTHtmlTagListContainer class]] || [container isKindOfClass:[XTHtmlTagLi class]]) {
			res = YES;
		} else if (container.cachedIsEnclosedByListOrListItem != nil) {
			res = container.cachedIsEnclosedByListOrListItem.boolValue;
		}
	}
	
	return res;
}

//TODO !!! refactor: impl using findAncestorTagContainerOfClass:
+ (XTHtmlTagListContainer *)listContainerFor:(XTHtmlTag *)tag
{
	XTHtmlTagListContainer *res = nil;
	
	for (XTHtmlTagContainer *container = tag.container;
		 container != nil && res == NO;
		 container = container.container) {
		
		if ([container isKindOfClass:[XTHtmlTagListContainer class]]) {
			res = (XTHtmlTagListContainer *) container;
		}
	}
	
	return res;
}

+ (XTHtmlTagContainer *)findAncestorTagContainerOfClass:(Class)aClass
									   forDescendantTag:(XTHtmlTag *)descendantTag
									  includeDescendant:(BOOL)includeDescendant
{
	XTHtmlTagContainer *res = nil;
	
	for (XTHtmlTagContainer *container = includeDescendant ? (XTHtmlTagContainer *)descendantTag : descendantTag.container;
		 container != nil && res == nil;
		 container = container.container) {
		
		if ([container isKindOfClass:aClass]) {
			res = container;
		}
	}
	
	return res;
}

@end
