package com.supervision.config;

import io.minio.MinioClient;
import io.minio.SetBucketLifecycleArgs;
import io.minio.errors.*;
import io.minio.messages.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Endpoint	对象存储服务的URL
 * Access Key	Access key就像用户ID,可以唯一标识你的账户。
 * Secret Key	Secret key是你账户的密码。
 *
 * @author qmy
 * @since 1.0.0
 */
@Configuration
public class MinioConfig {

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

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

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

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


    @Bean
    @Primary
    public MinioClient minioClient() {
        // Create a minioClient with the MinIO server playground, its access key and secret key.
        MinioClient client = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        try {
            client.setBucketLifecycle(
                    SetBucketLifecycleArgs
                            .builder()
                            .config(new LifecycleConfiguration(
                                    List.of(
                                            new LifecycleRule(Status.ENABLED,
                                                    null,
                                                    new Expiration((ResponseDate) null, 1, null),
                                                    new RuleFilter("temp-"),
                                                    "TempFileDeleteRule",
                                                    null,
                                                    null,
                                                    null)
                                    )
                            ))
                            .bucket(bucketName)
                            .build()
            );
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException |
                 XmlParserException e) {
            throw new RuntimeException(e);
        }
        return client;
    }

}