package kr.iotdoor.boot.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;

import java.nio.charset.StandardCharsets;
import java.nio.file.Path;

@Configuration
@ConditionalOnProperty(prefix = "iotdoor.dev-template", name = "enabled", havingValue = "true", matchIfMissing = true)
public class DevelopmentTemplateConfig {

    private static final Path SOURCE_TEMPLATE_PATH = Path.of("src/main/resources/templates")
        .toAbsolutePath()
        .normalize();

    @Bean
    public SpringResourceTemplateResolver sourceTemplateResolver(ApplicationContext applicationContext) {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix(toFilePrefix(SOURCE_TEMPLATE_PATH));
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resolver.setCheckExistence(true);
        resolver.setCacheable(false);
        resolver.setOrder(0);
        return resolver;
    }

    private String toFilePrefix(Path path) {
        String uri = path.toUri().toString();
        return uri.endsWith("/") ? uri : uri + "/";
    }
}
