package com.xjrsoft.common.factory;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.xjrsoft.config.OSSConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author : tzx
 */
public class MinioService extends CloudStorageService {
    private MinioClient client;

    public MinioService(OSSConfig config){
        this.config = config;

        //初始化
        init();
    }

    @SneakyThrows
    private void init(){
        client = MinioClient.builder().endpoint(config.getEndpoint()).credentials(config.getAccessKey(),config.getSecretKey()).build();
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                            .bucket(config.getBucketName())
                                    .object(path).stream(inputStream,inputStream.available(), -1).build();
            client.putObject(args);
        } catch (Exception e){
            throw new RuntimeException("上传文件失败，请检查配置信息", e);
        }
        if (!config.getEndpointPreview().isEmpty()){
            return config.getEndpointPreview() + StringPool.SLASH + config.getBucketName() +  StringPool.SLASH + path;
        }else{
            return config.getEndpoint() + StringPool.SLASH + config.getBucketName() +  StringPool.SLASH + path;
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getPrefix(), suffix));
    }

    @Override
    public boolean delete(String objectName) {
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(config.getBucketName())
                    .object(objectName).build();
            client.putObject(args);
        } catch (Exception e){
            throw new RuntimeException("删除文件失败，请检查配置信息", e);
        }
        return true;
    }
}

