package com.utopiaindustries.dialect;

import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;

public class IsOnPathTagProcessor extends AbstractAttributeTagProcessor {
	private static final String ATTR_NAME = "is-on-path";
	private static final int PRECEDENCE = 100000;

	public IsOnPathTagProcessor( final String dialectPrefix ) {
		super(
				TemplateMode.HTML,
				dialectPrefix,
				null,
				false,
				ATTR_NAME,
				true,
				PRECEDENCE,
				true
		);
	}

	/**
	 * this tag accepts paths as params with the path to check against as the last argument
	 */
	protected void doProcess( ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, AttributeName attributeName, String attributeValue, IElementTagStructureHandler iElementTagStructureHandler ) {
		final IEngineConfiguration configuration = iTemplateContext.getConfiguration();
		final IStandardExpressionParser parser = StandardExpressions.getExpressionParser( configuration );
		final IStandardExpression expression = parser.parseExpression( iTemplateContext, attributeValue );
		final String[] attributeValueParsed = ( ( String ) expression.execute( iTemplateContext ) ).split( "," );
		// the target path is the last argument
		final String targetPath = attributeValueParsed[attributeValueParsed.length - 1];
		boolean matched = false;
		// iterate over paths (except the last one, since thats the target path)
		// and check if any thing matched
		for ( int i = 0; i < attributeValueParsed.length - 1; i++ ) {
			if ( targetPath.contains( attributeValueParsed[i] ) ) {
				matched = true;
				break;
			}
		}
		// remove body if didn't match
		if ( ! matched ) {
			iElementTagStructureHandler.removeElement();
		}
	}
}
