package com.copy.trade.util;

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.AmazonS3ClientBuilder;
import com.copy.trade.bean.S3Config;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

public class OssUtil {

    private static AmazonS3 getS3Client(S3Config s3Config) {
        BasicAWSCredentials credentials = new BasicAWSCredentials(
                s3Config.getAccessKeyId(), s3Config.getAccessKeySecret());
        if (s3Config.getEndpoint() != null && !s3Config.getEndpoint().isEmpty()) {
            return AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
                            s3Config.getEndpoint(), s3Config.getRegion()))
                    .build();
        }
        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(s3Config.getRegion())
                .build();
    }

    /**
     * 获得文件访问路径（预签名URL，1小时有效）
     */
    public static String getUrl(String objectName, boolean isPrivate, S3Config s3Config) {
        AmazonS3 s3Client = getS3Client(s3Config);
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        URL url = s3Client.generatePresignedUrl(s3Config.getBucketName(), objectName, expiration);
        s3Client.shutdown();
        return url.toString();
    }

    /**
     * 上传文件到S3
     */
    public static String upload(InputStream inputStream, String objectName, boolean isPrivate, S3Config s3Config) {
        AmazonS3 s3Client = getS3Client(s3Config);
        s3Client.putObject(s3Config.getBucketName(), objectName, inputStream, null);
        s3Client.shutdown();
        return s3Config.toUrl(objectName);
    }

    /**
     * 复制流
     */
    public static ByteArrayOutputStream cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
