package cn.quantgroup.customer.config.http.security;

import cn.quantgroup.customer.config.http.mvc.converter.IntegerToEnumConverterFactory;
import cn.quantgroup.customer.constant.Constant;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;

import java.text.SimpleDateFormat;


@EnableRedisHttpSession(maxInactiveIntervalInSeconds = Constant.COOKIE_AND_SESSION_EXPIRE_TIMEOUT_SECONDS)
public class WebSessionConfig {
    @Bean(name = "httpSessionStrategy")
    public HttpSessionStrategy httpSessionStrategy() {
        HeaderHttpSessionStrategy strategy = new HeaderHttpSessionStrategy();
        return strategy;
    }


    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.indentOutput(false)
                .dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .defaultViewInclusion(false)
                .serializationInclusion(JsonInclude.Include.NON_NULL)
                .featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_INDEX,
                        DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
        return builder;
    }

    @Bean
    public ConverterRegistry defaultConversionService() {
        FormattingConversionService conversionService = new DefaultFormattingConversionService();
        addFormatter(conversionService);
        return conversionService;
    }

    @Bean
    public ConverterRegistry integrationConversionService() {
        FormattingConversionService conversionService = new DefaultFormattingConversionService();
        addFormatter(conversionService);
        return conversionService;
    }


    private void addFormatter(FormattingConversionService conversionService) {
        IntegerToEnumConverterFactory factory = new IntegerToEnumConverterFactory();
        conversionService.removeConvertible(String.class, Enum.class);
        conversionService.addConverterFactory(factory);
    }

}
