package com.sptg.common.tag.cfgbeans;

import com.sptg.common.tag.dialect.CustomDialect;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ITemplateResolver;

import java.util.Collection;

/**
 * title: ThymeleafAutoConfigBean
 * package: com.sptg.common.tag.cfgbeans
 * description:
 *
 *                  
 *                 
 */
@Configuration
public class ThymeleafAutoConfigBean {


    @Configuration
    @ConditionalOnMissingBean(SpringTemplateEngine.class)
    protected static class ThymeleafDefaultConfiguration {

        private final Collection<ITemplateResolver> templateResolvers;

        private final Collection<IDialect> dialects;

        public ThymeleafDefaultConfiguration(
                Collection<ITemplateResolver> templateResolvers,
                ObjectProvider<Collection<IDialect>> dialectsProvider) {
            this.templateResolvers = templateResolvers;
            this.dialects = dialectsProvider.getIfAvailable();
        }

        @Bean
        public SpringTemplateEngine templateEngine() {
            SpringTemplateEngine engine = new SpringTemplateEngine();
            this.templateResolvers.forEach(engine::addTemplateResolver);
            if (!CollectionUtils.isEmpty(this.dialects)) {
                this.dialects.forEach(engine::addDialect);
            }
            //  加入自定义方言
            engine.addDialect(new CustomDialect());
            return engine;
        }

    }

}
