package xyz.wbsite.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xyz.wbsite.frame.provider.SimpleTokenProvider;
import xyz.wbsite.frame.provider.SimpleUserProvider;
import xyz.wbsite.frame.provider.TokenProvider;
import xyz.wbsite.frame.provider.UserProvider;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${web.url.index}")
    private String homePage;
    @Value("${spring.mvc.static-path-pattern}")
    private String[] staticPath;

    /**
     * 增加全局拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 全局拦截器
        registry.addInterceptor(new HandlerInterceptorAdapter() {

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                super.afterCompletion(request, response, handler, ex);
            }

        }).addPathPatterns("/**").excludePathPatterns(staticPath);
    }

    /**
     * 跨域配置
     *
     * @param registry
     */
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedOrigins("*")
//                .allowCredentials(true)
//                .allowedMethods("GET", "POST", "DELETE", "PUT")
//                .maxAge(3600);
//    }

    /**
     * Jackson序列化时的转化规则配置
     *
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
                SimpleModule simpleModule = new SimpleModule();
                {// 序列化时：Long或long类型在转String，防止出现javascript中Number精度丢失的情况。
                    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
                    simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
                }

                {// 反序列化时：Boolean和boolean可以识别0和1数字
                    simpleModule.addDeserializer(Boolean.class, new JsonDeserializer<Boolean>() {
                        @Override
                        public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                            String text = jsonParser.getText();
                            if (text == null || "".equals(text)) {
                                return null;
                            } else {
                                return text.matches("1|true");
                            }
                        }
                    });
                    simpleModule.addDeserializer(Boolean.TYPE, new JsonDeserializer<Boolean>() {
                        @Override
                        public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
                            String text = jsonParser.getText();
                            if (text == null || "".equals(text)) {
                                return false;
                            } else {
                                return text.matches("1|true");
                            }
                        }
                    });
                    objectMapper.registerModule(simpleModule);
                }
                objectMapper.registerModule(simpleModule);
            }
        }
    }

    /**
     * 当未提供用户提供者时，注册一个简单的用户提供者
     *
     * @return 简单的提供者
     */
    @Bean
    @ConditionalOnMissingBean
    public UserProvider userProviderImpl() {
        return new SimpleUserProvider();
    }

    /**
     * 当未提供同行证提供者，注册一个简单同行证提供者
     *
     * @return 简单的提供者
     */
    @Bean
    @ConditionalOnMissingBean
    public TokenProvider tokenProviderImpl() {
        return new SimpleTokenProvider();
    }
}