package com.utopiaindustries.dialect;

import com.utopiaindustries.util.CTPDateTimeFormat;
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;
import java.time.format.DateTimeFormatter;

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

    public FormatTimeTagProcessor( 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 LocalDateTime attributeValueParsed = ( LocalDateTime ) expression.execute( iTemplateContext );
        // format zoned date time
        String formattedDateTime = attributeValueParsed.format( DateTimeFormatter.ofPattern( CTPDateTimeFormat.HTML5_TIME_INPUT_FORMAT_ATTENDANCE ) );
        // render the body
        iElementTagStructureHandler.setBody( formattedDateTime, false );
    }

}
