package io.wdd.func.oss.config;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 从Nacos中获取配置，获取所有S3的配置，并且自动更新
 * <p>
 * https://developer.aliyun.com/article/1111261
 * https://www.cnblogs.com/cndarren/p/16833526.html
 */
@Configuration
@ConfigurationProperties(prefix = "oss")
@Data
@RefreshScope
public class OSSConfiguration {

    /**
     * 缓存所有的S3的配置对象
     */
    public static final List<OssConfig> ALL_OSS_CONFIG = new ArrayList<>();

    /**
     * 初始数据
     */
    private LinkedHashMap<String, LinkedHashMap<String, String>> oracle = new LinkedHashMap<>();


    @PostConstruct
    public void buildAllS3Client() {

        oracle
                .entrySet()
                .stream()
                .forEach(
                        entry -> {

                            LinkedHashMap<String, String> entryValue = entry.getValue();

                            OssConfig ossConfig = OssConfig
                                    .builder()
                                    .name(entry.getKey())
                                    .namespace(entryValue.get("namespace"))
                                    .region(entryValue.get("region"))
                                    .key(entryValue.get("key"))
                                    .secret(entryValue.get("secret"))
                                    .build();


                            AmazonS3 client = buildS3ClientFromOssConfig(ossConfig);

                            ossConfig.setClient(client);


                            // 添加进入全局cache
                            ALL_OSS_CONFIG.add(ossConfig);

                            //  todo 异步任务,查询 已使用的容量, 写入ossConfig中
                            //
                        }
                );


        // help gc
        oracle = null;

    }

    private AmazonS3 buildS3ClientFromOssConfig(OssConfig ossConfig) {


        AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials(
                ossConfig.getKey(),
                ossConfig.getSecret()
        ));

        String oracleOSSEndpoint = buildOracleOSSEndpoint(
                ossConfig.getNamespace(),
                ossConfig.getRegion()
        );
        // Create an S3 client pointing at the region
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder
                .EndpointConfiguration(
                oracleOSSEndpoint,
                ossConfig.getRegion()
        );

        return AmazonS3Client
                .builder()
                .standard()
                .withCredentials(credentials)
                .withEndpointConfiguration(endpointConfiguration)
                .disableChunkedEncoding()
                .enablePathStyleAccess()
                .build();
    }

    private String buildOracleOSSEndpoint(String namespace, String region) {

        return String.format(
                "%s.compat.objectstorage.%s.oraclecloud.com",
                namespace,
                region
        );
    }

    /**
     * 从Nacos中获取到所有的对象存储对象
     *//*
    @Value("${oss.oracle.seoul2.region}")
    String SeoulRegion;
    @Value("${oss.oracle.seoul2.namespace}")
    String Seoul2Namespace;
    @Value("${oss.oracle.seoul2.key}")
    String Seoul2Key;
    @Value("${oss.oracle.seoul2.secret}")
    String Seoul2Secret;*/
}
