package cn.reghao.tnb.file.app.service;

import cn.reghao.tnb.file.app.model.po.StoreConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * @author reghao
 * @date 2024-08-30 16:13:38
 */
@Service
public class AliyunOss {
    private String bucketName;
    private OSS ossClient;

    public void init(StoreConfig storeConfig) {
        String endpoint = storeConfig.getEndpoint();
        String accessKeyId = storeConfig.getAccessKeyId();
        String accessKeySecret = storeConfig.getAccessKeySecret();
        this.bucketName = storeConfig.getBucketName();
        this.ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    public void uploadObject(String objectName, File file) throws IOException {
        System.out.println("Uploading a new object to OSS from a file\n");
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
        putObjectRequest.setMetadata(objectMetadata);
        ossClient.putObject(putObjectRequest);
    }

    public void downloadObject(String objectName) throws IOException {
        System.out.println("Downloading an object");
        OSSObject object = ossClient.getObject(bucketName, objectName);
        System.out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());
    }

    private void displayTextInputStream(InputStream input) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;

            System.out.println("    " + line);
        }
        System.out.println();

        reader.close();
    }

    public void deleteObject(String objectName) {
        ossClient.deleteObject(bucketName, objectName);
    }

    public void listObjects(String prefix) {
        System.out.println("Listing objects");
        ObjectListing objectListing = ossClient.listObjects(bucketName, prefix);
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            String objectName = objectSummary.getKey();
            long size = objectSummary.getSize();
            if (size != 0) {
                //deleteObject(objectName);
            }

            System.out.println(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();
    }

    public void close() {
        ossClient.shutdown();
    }

    public String getSignedUrl(String objectName) {
        int expireSecond = 3600;
        long timestamp = System.currentTimeMillis() + expireSecond*1000L;
        Date expiration = new Date(timestamp);
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        return url.toString();
    }

    public static void main(String[] args) throws IOException {
        /*String accessKeyId = System.getenv("ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ACCESS_KEY_SECRET");
        AliyunOss aliyunOss = new AliyunOss();
        aliyunOss.init();

        String objectName = "uploads/v2-283f0faab9f27a345e2e86070580e8d8_r.jpg";
        String signedUrl = aliyunOss.getSignedUrl(objectName);
        System.out.println(signedUrl);*/

        /*String baseDir = "";
        File dir = new File(baseDir);
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                continue;
            }

            String filename = file.getName();
            String objectName = String.format("%s%s", objectNamePrefix, filename);
            uploadObject(objectName, file);
        }*/

        /*String objectName = "dev/test/1.txt";
        File file = createSampleFile();*/

        /*String objectNamePrefix = "mmexport/";
        aliyunOss.listObjects(objectNamePrefix);*/
    }
}
