/* (C) 2022 YiRing, Inc. */
package com.yiring.common.config;

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.yiring.common.constant.DateFormatter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

/**
 * DateTime Config
 *
 * @author ifzm
 * 2020/7/8 00:35
 */

@Configuration
public class DateTimeConfig {

    @Bean
    public JavaTimeModule javaTimeModule() {
        JavaTimeModule timeModule = new JavaTimeModule();
        timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateFormatter.DATE_TIME));
        timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateFormatter.DATE));
        timeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateFormatter.TIME));
        timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateFormatter.DATE_TIME));
        timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateFormatter.DATE));
        timeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateFormatter.TIME));
        return timeModule;
    }

    @Bean
    public StringToLocalDateTimeConverter localDateTimeConverter() {
        return source -> LocalDateTime.parse(source, DateFormatter.DATE_TIME);
    }

    @Bean
    public StringToLocalDateConverter localDateConverter() {
        return source -> LocalDate.parse(source, DateFormatter.DATE);
    }

    @Bean
    public StringToLocalTimeConverter localTimeConverter() {
        return source -> LocalTime.parse(source, DateFormatter.TIME);
    }

    public interface StringToLocalDateTimeConverter extends Converter<String, LocalDateTime> {}

    public interface StringToLocalDateConverter extends Converter<String, LocalDate> {}

    public interface StringToLocalTimeConverter extends Converter<String, LocalTime> {}
}
