package com.sunyard.chsm.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.sunyard.chsm.auth.AuthHandler;
import com.sunyard.chsm.utils.DateFormat;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author liulu
 * @since 2024/12/6
 */
@Configuration
public class WebConfig {


    @Bean
    public WebMvcConfigurer webMvcConfigurer(AuthHandler authHandler) {
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(authHandler).addPathPatterns("/**");
            }
        };
    }


    @Bean
    public Jackson2ObjectMapperBuilderCustomizer objectMapperBuilderCustomizer() {
        return builder -> {
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateFormat.TIME));
            javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateFormat.DATE));
            javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateFormat.DATE_TIME));

            javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateFormat.TIME));
            javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateFormat.DATE));
            javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateFormat.DATE_TIME));
            builder.modules(javaTimeModule);
            builder.serializerByType(Long.class, ToStringSerializer.instance);
            builder.serializationInclusion(JsonInclude.Include.NON_NULL);
            builder.failOnUnknownProperties(false);
        };
    }

}
