package com.ho.business.common;

import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.List;

/**
 * @Author yule
 * @Date 2023/05/05 11:03
 */
@Slf4j
@Configuration
public class MinioClientConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinioClientConfig.class);

 /*
    private static MinioClient minioClient;*/



    /**
     * @description: 获取minioClient
     * @date 2021/6/22 16:55
     * @return io.minio.MinioClient
     */
/*    public static MinioClient getMinioClient(){
        return minioClient;
    }*/
 
    /**
     * 判断 bucket是否存在
     *
     * @param bucketName:
     *            桶名
     * @return: boolean
     * @date : 2020/8/16 20:53
     */
    @SneakyThrows(Exception.class)
    public static boolean bucketExists(String bucketName) {
        //return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        return true;
    }
 
 
    /**
     * 获取全部bucket
     *
     * @param :
     * @return: java.util.List<io.minio.messages.Bucket>
     * @date : 2020/8/16 23:28
     */
    @SneakyThrows(Exception.class)
    public static List<Bucket> getAllBuckets() {
        //return minioClient.listBuckets();
        return null;
    }


    @Value("${minio.endpoint}")
    String endpoint;

    @Value("${minio.accessKey}")
    String accessKey;

    @Value("${minio.secretKey}")
    String secretKey;



    /**
     * 初始化minio配置
     *
     * @param :
     * @return: void
     * @date : 2020/8/16 20:56
     */


    @Bean
    public MinioClient minioClient() {

        OkHttpClient customHttpClient = null;
        if (endpoint.startsWith("https://")) {
            // 如果是HTTPS，使用自定义的OkHttpClient处理自签名的HTTPS请求
            customHttpClient = createCustomOkHttpClient();
        }

        MinioClient minioClient;
        if (customHttpClient != null) {
            // 如果使用了自定义的OkHttpClient
            minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .httpClient(customHttpClient)
                    .build();

        } else {
            // 如果是普通HTTP，使用默认的OkHttpClient
            minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();

        }
        return minioClient;

    }

    private static OkHttpClient createCustomOkHttpClient() {
        // 创建自定义的OkHttpClient，用于处理自签名的HTTPS请求

        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        // Do nothing (trust any client certificate)
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        // Do nothing (trust any server certificate)
                    }
                }
        };

        // Install the all-trusting trust manager
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());
        } catch (Exception e) {
            LOGGER.error("Install the all-trusting trust manager error:{}", e.getMessage());
        }


        // Create a custom OkHttpClient that trusts all certificates
        OkHttpClient customHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                .hostnameVerifier((hostname, session) -> true)
                // 增加minio http请求日志打印
                .addInterceptor(new CustomLoggingInterceptor()) // Add custom interceptor here
                .build();
        return customHttpClient;
    }
 
}
