package com.elab.spring.config;

import com.elab.spring.utils.RestTemplateUtils;
import com.elab.spring.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 公共的基于注解的配置文件定义
 *
 * @author : liukx
 * @create : 2018/6/4 16:49
 * @email : liukx@elab-plus.com
 */
@Configuration
@Import(value = {SpringUtils.class})
public class SpringCommonConfig {

    @Bean
    public ClientHttpRequestFactory getClientHttpRequestFactory(@Autowired Environment environment) {
        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setConnectTimeout(Integer.valueOf(environment.getProperty("httpClient.connect.timeOut", "120000")));
        simpleClientHttpRequestFactory.setReadTimeout(Integer.valueOf(environment.getProperty("httpClient.read.timeOut", "120000")));
        return simpleClientHttpRequestFactory;
    }

    @Bean
    public RestTemplate getRestTemplate(@Autowired Environment environment) {
        RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory(environment));
        return restTemplate;
    }

    @Bean
    public RestTemplateUtils restTemplateUtils(@Autowired RestTemplate restTemplate) {
        RestTemplateUtils restTemplateUtils = new RestTemplateUtils();
        restTemplateUtils.setRestTemplate(restTemplate);
        return restTemplateUtils;
    }

    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer(@Autowired Environment environment) throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(environment.getProperty("spring.resources.path", "classpath:*.properties"));
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setLocations(resources);
        configurer.setSearchSystemEnvironment(true);
        configurer.setIgnoreResourceNotFound(true);
        return configurer;
    }
}
