package com.njzscloud.common.oss.config;


import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.njzscloud.common.oss.controller.OSSController;
import com.njzscloud.common.oss.service.AliService;
import com.njzscloud.common.oss.service.MinioService;
import com.njzscloud.common.oss.service.OSSService;
import io.minio.MinioAsyncClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(OSSProperties.class)
public class OSSAutoConfiguration {

    @Bean(destroyMethod = "close")
    @ConditionalOnProperty(prefix = "oss", name = "type", havingValue = "minio")
    public MinioAsyncClient minioClient(OSSProperties ossProperties) {
        OSSProperties.MinioProperties minio = ossProperties.getMinio();
        String endpoint = minio.getEndpoint();
        String accessKey = minio.getAccessKey();
        String secretKey = minio.getSecretKey();
        return MinioAsyncClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(prefix = "oss", name = "type", havingValue = "ali")
    public OSS ossClient(OSSProperties ossProperties) {
        OSSProperties.AliProperties ali = ossProperties.getAli();
        String endpoint = ali.getEndpoint();
        String accessKey = ali.getAccessKey();
        String secretKey = ali.getSecretKey();
        String region = ali.getRegion();

        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(accessKey, secretKey);
        return OSSClientBuilder.create()
                .endpoint(endpoint)
                .region(region)
                .credentialsProvider(credentialProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .build();
    }

    @Bean
    public OSSService ossService(OSSProperties ossProperties) {
        OSSType type = ossProperties.getType();
        switch (type) {
            case ali:
                return new AliService();
            case minio:
                return new MinioService();
            default:
                return null;
        }
    }

    @Bean
    public OSSController ossController(OSSService ossService) {
        return new OSSController(ossService);
    }
}
