package com.sifang.modules.config;


import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.sifang.modules.sys.common.global.Global;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Lazy;

import java.io.File;
import java.util.concurrent.TimeUnit;

@EnableAspectJAutoProxy
@Configuration
public class AppConfig {

    private static final Logger log = LoggerFactory.getLogger(AppConfig.class);

    @Bean
    @Lazy
    public AmazonS3Client awss3() {
        String ak = Global.getConfig("s3.ak");
        String secret = Global.getConfig("s3.secret");
        BasicAWSCredentials basicAwsCred = new BasicAWSCredentials(ak, secret); //请替换成您的AccessKey和SecretKey
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);
        AmazonS3Client s3 = new AmazonS3Client(basicAwsCred,clientConfiguration);
        S3ClientOptions options = S3ClientOptions.builder().setPathStyleAccess(true).setPayloadSigningEnabled(true).disableChunkedEncoding().build();
        s3.setS3ClientOptions(options);
        s3.setEndpoint(Global.getConfig("s3.endpoint"));
        return s3;
    }

    @Bean
    public OkHttpClient okHttpClient() {
        String tmpDirsLocation = System.getProperty("java.io.tmpdir");
        File cacheDirObj = new File(new File(tmpDirsLocation, "cache"), "okhttp3");
        if (!cacheDirObj.mkdirs() && !cacheDirObj.exists()) {
            log.info("create cache dir for okhttp3 fail");
        }
        String cacheDir = cacheDirObj.getAbsolutePath();
        File dir = new File(cacheDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException("cannot mkdir :" + cacheDir);
            }
        }


        Interceptor cacheIt = chain -> {
            Request request = chain.request();
            Response response = chain.proceed(request);

            String cacheCtrlHeaderVal = request.header("Cache-Control");
            if (StringUtils.isBlank(cacheCtrlHeaderVal)) {
                return response;
            }

            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", cacheCtrlHeaderVal)
                    .build();
        };

        Interceptor loggingIt = chain -> {
            long t1 = System.nanoTime();
            Request request = chain.request();
            log.info(String.format("Request [%s] on %s%n%s", request.url(), chain.connection(), request.headers()));
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            log.info(String.format("Response [%s] in %.1fms%n%s", request.url(), (t2 - t1) / 1e6d, response.headers()));
            return response;
        };

        return new OkHttpClient()
                .newBuilder()
                .retryOnConnectionFailure(true) // this default
                .connectionPool(pool())
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .cache(new Cache(new File(cacheDir), 1024 * 1024 * 1024)) // 1g
                .addNetworkInterceptor(cacheIt)
                .addNetworkInterceptor(loggingIt)
                .build();

    }

    @Bean
    public ConnectionPool pool() {
        return new ConnectionPool(50, 10, TimeUnit.MINUTES);
    }

}
