import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.ScheduledLockConfiguration;
import net.javacrumbs.shedlock.spring.ScheduledLockConfigurationBuilder;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.sql.DataSource;
import java.time.Duration;

/**
 * Root application context
 * This context imports XML configs from all the other jars, and is created by {@link WebAppInitializer}
 * NB: modules are excluded from component scan since spring-context.xml sometimes holds important parameters and / or annotations
 * @author krylov
 */
@Configuration
@ComponentScan(basePackages = {
    "service",
    "dao",
    "bpmn",
    "i18n",
    "errorhandling",
    "database",
    "security",
    "component.addresses",
    "gen",
    "ru.cg",
    "ru.micord"
})
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableWebMvc
@EnableScheduling
public class AppConfig {

  @Value("${config.data.executor.socket.timeout:10}")
  private int socketTimeout;
  @Value("${config.data.executor.connection.timeout:10}")
  private int connectionTimeout;

  @Bean
  public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
    return new PropertySourcesPlaceholderConfigurer();
  }

  @Bean
  public ScheduledLockConfiguration taskScheduler(LockProvider lockProvider) {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(12);
    scheduler.initialize();
    return ScheduledLockConfigurationBuilder
        .withLockProvider(lockProvider)
        .withTaskScheduler(scheduler)
        .withDefaultLockAtMostFor(Duration.ofHours(4))
        .build();
  }

  @Bean
  public LockProvider lockProvider(@Qualifier("datasource") DataSource dataSource) {
    return new JdbcTemplateLockProvider(dataSource);
  }

  @Bean
  public RestTemplate restTemplate() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout * 1000)
            .setConnectionRequestTimeout(connectionTimeout * 1000)
            .setConnectTimeout(connectionTimeout * 1000)
            .build();

    CloseableHttpClient httpClient = HttpClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .build();

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

    return new RestTemplate(factory);
  }
}
