package com.utopiaindustries.dialect;

import com.utopiaindustries.util.TimePeriodFormatter;
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;

import java.time.LocalDateTime;

public class FormatTimePeriodHumanReadableBetween extends AbstractAttributeTagProcessor {
	private static final String ATTR_NAME = "humanreadableperiodbetween";
	private static final int PRECEDENCE = 100000;

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

	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 );
		// get arguments from comma separated list
		String[] args = attributeValueParsed.split( "," );
		LocalDateTime from = LocalDateTime.parse( args[0] );
		LocalDateTime to = LocalDateTime.parse( args[1] );
		// formatted time period
		String formattedPeriod = ( new TimePeriodFormatter() )
				.from( from )
				.to( to )
				.format();
		// render the body
		iElementTagStructureHandler.setBody( formattedPeriod, false );
	}
}
