package cn.com.ctop.track.util;



import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
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.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @description: todo
 * @author: sunrui62
 * @create: 2023/3/23 2:23 下午
 **/
public class OssDemo {
    private static AmazonS3 s3;

    private static final String accessKey = "JDC_F2DA04429F388D7E2167871292BB";
    private static final String secretKey = "1BEEB211BC8DFBE30A17FAD6750571EA";
    private static final String endpoint = "s3.cn-north-1.jdcloud-oss.com";
    private static final String region = "oss-match-upload";
    static {
        s3 = init(accessKey, secretKey, endpoint, region);
    }


    private static final String bucketName = "test-space-sr";
    public static void main(String[] args) throws Exception{
        // 上传文件
        String uploadFilePath = "cps/sunrui_test2/20230322/imei/input/qianfan.csv.0001";
        uploadStream(bucketName, uploadFilePath, "imei1\nimei2");
        // 获取文件内容
        String content = getObjectContent(bucketName, uploadFilePath);
        System.out.println(content);

        // 阻塞获取output内容
        while (true) {
            boolean continueFlag = true;
            try {
                String successFilePath = "cps/sunrui_test2/20230322/imei/output/SUCCESS";
                String successContent = getObjectContent(bucketName, successFilePath);
                System.out.println("获取到文件，内容是：" + successContent);
                continueFlag = false;
            } catch (AmazonS3Exception e) {
                System.out.println("文件还没有生成，等会接着获取");
                Thread.sleep(10000);
            } catch (Exception e){
                e.printStackTrace();
                continueFlag = false;
            }
            if (!continueFlag){
                break;
            }
        }
    }

    /**
     * 初始化客户端
     * @param accessKey
     * @param secretKey
     * @param endpoint
     * @return
     */
    private static AmazonS3 init(String accessKey, String secretKey, String endpoint, String region) {
        ClientConfiguration config = new ClientConfiguration();
        AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(endpoint, region);

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

        AmazonS3 s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .build();
        return s3;
    }


    /**
     * @param bucketName
     * @param filePath
     * @param data
     */
    public static void uploadStream(String bucketName, String filePath, String data) {
        byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
        InputStream bais = new ByteArrayInputStream(byteData);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        s3.putObject(bucketName, filePath, bais, objectMetadata);
    }

    /**
     * 获取文件内容
     * @param bucketName
     * @param filePath
     * @return
     * @throws Exception
     */
    private static String getObjectContent(String bucketName, String filePath) throws Exception{
        S3Object s3Object = s3.getObject(bucketName, filePath);
        S3ObjectInputStream s3is = s3Object.getObjectContent();

        BufferedReader bufferedReader = getReader(s3is, null);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(System.lineSeparator());
        }

        return stringBuilder.toString();
    }

    /**
     * 获得一个Reader
     *
     * @param in      输入流
     * @param charset 字符集
     * @return BufferedReader对象
     */
    private static BufferedReader getReader(InputStream in, Charset charset) {
        if (null == in) {
            return null;
        }
        InputStreamReader reader;
        if (null == charset) {
            reader = new InputStreamReader(in);
        } else {
            reader = new InputStreamReader(in, charset);
        }
        return new BufferedReader(reader);
    }

}
