package com.uas.eis.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uas.eis.core.support.ApiSignLoginInterceptor;
import com.uas.eis.core.support.DataSourceInterceptor;
import com.uas.eis.core.support.LoginInterceptor;
import com.uas.eis.core.support.MesHelperApiLoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.List;

@Configuration
public class WebAppConfig extends WebMvcConfigurationSupport{

	@Bean
	public LoginInterceptor loginInterceptor(){
		return new LoginInterceptor();
	}

	@Bean
	public ApiSignLoginInterceptor apiSignLoginInterceptor(){
		return new ApiSignLoginInterceptor();
	}

	@Bean
	public MesHelperApiLoginInterceptor mesHelperApiLoginInterceptor(){
		return new MesHelperApiLoginInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry){
		registry.addInterceptor(apiSignLoginInterceptor()).addPathPatterns("/api/**","/mes/**")
				.excludePathPatterns("/login", "/erp/**");
		registry.addInterceptor(mesHelperApiLoginInterceptor()).addPathPatterns("/MES/helper/**");
		//registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/EIS/login");
		registry.addInterceptor(new DataSourceInterceptor()).addPathPatterns("/*/**");
	}
	
	@Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }

	@Bean
	public MappingJackson2HttpMessageConverter MappingJacksonHttpMessageConverter(){
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		converter.setObjectMapper(objectMapper);
		return converter;
	}
	
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
        converters.add(MappingJacksonHttpMessageConverter());
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}
