package com.cnd3b.utility.obs;

import com.cnd3b.utility.WebRequest;
import com.obs.services.internal.utils.ServiceUtils;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import com.obs.services.model.fs.DropFolderRequest;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class BucketFile extends Bucket {

    public BucketFile(String siteid) {
        super(siteid);
    }

    /**
     * 流文件上传，如果文件类型是图片,则会自动生成缩略图
     */
    public void upload(String filename, InputStream inputStream, boolean iscreateMinImage) {
        obsClient.putObject(bucketname, filename, inputStream);

        /**
         * 如果是图片文件，则同时生成一个缩略图文件
         */
        if (iscreateMinImage) {
            String filename_short = "s_" + filename;
            //临时访问地址有效时间
            // 创建ObsClient实例
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 3600);
            request.setBucketName(bucketname);
            request.setObjectKey(filename);

            // 设置图片处理参数，对图片依次进行缩放、旋转
            Map<String, Object> queryParams = new HashMap<String, Object>();
            queryParams.put("x-image-process", "image/resize,m_lfit,h_150");
            try {
                queryParams.put("x-image-save-object", ServiceUtils.toBase64(filename_short.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.setQueryParams(queryParams);
            // 生成临时授权URL
            TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
            //临时访问，生成缩略图（华为云在第一次访问该地址时才会生成实体文件）
            new WebRequest().doGet_simple(response.getSignedUrl());
        }
    }

    /**
     * 文件删除,如果存在缩略文件，则缩略文件会一起删除
     *
     * @param objectname
     */
    public void deleteFile(String objectname) {
        obsClient.deleteObject(bucketname, objectname);
        if (obsClient.doesObjectExist(bucketname, "s_" + objectname)) {
            obsClient.deleteObject(bucketname, "s_" + objectname);
        }
        if (obsClient.doesObjectExist(bucketname, "c_" + objectname)) {
            obsClient.deleteObject(bucketname, "c_" + objectname);
        }
    }

    public void deleteFolder(String foldername) {
        DropFolderRequest dropFolderRequest = new DropFolderRequest(bucketname, foldername);
        obsClient.dropFolder(dropFolderRequest);
    }

    public boolean doesObjectExist(String objectname) {
        return obsClient.doesObjectExist(bucketname, objectname);
    }

    /**
     * 获取文件下载地址
     */
    public String getFileUrl(String filename) {
        //临时访问地址有效时间
        //long expireSeconds = 3600L;
        // 创建ObsClient实例
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 3600);
        request.setBucketName(bucketname);
        request.setObjectKey(filename);
        // 生成临时授权URL
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);

        //截取永久访问url，需要桶设置公共访问策略
        String url = response.getSignedUrl();
        return url.substring(0, url.indexOf("?"));
    }

    /**
     * 获取文件缩略图下载地址,缩略图的名称为在源文件的前面加上"s_"
     */
    public String getMinImageUrl(String filename) {
        /**
         * 缩略图名称
         */
        String filename_short = "s_" + filename;
        if (!obsClient.doesObjectExist(bucketname, filename_short)) {
            //临时访问地址有效时间
            // 创建ObsClient实例
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 3600);
            request.setBucketName(bucketname);
            request.setObjectKey(filename);

            // 设置图片处理参数，对图片依次进行缩放、旋转
            Map<String, Object> queryParams = new HashMap<String, Object>();
            queryParams.put("x-image-process", "image/resize,m_lfit,h_150");
            try {
                queryParams.put("x-image-save-object", ServiceUtils.toBase64(filename_short.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.setQueryParams(queryParams);
            // 生成临时授权URL
            TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
            //临时访问，生成缩略图（华为云在第一次访问该地址时才会生成实体文件）
            new WebRequest().doGet_simple(response.getSignedUrl());
        }
        return getFileUrl(filename_short);
    }

    /**
     * 获取文件缩略图下载地址,缩略图的名称为在源文件的前面加上"c_"
     */
    public String getCompressImageUrl(String filename) {
        /**
         * 缩略图名称
         */
        String filename_short = "c_" + filename;
        if (!obsClient.doesObjectExist(bucketname, filename_short)) {
            //临时访问地址有效时间
            // 创建ObsClient实例
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 3600);
            request.setBucketName(bucketname);
            request.setObjectKey(filename);

            // 设置图片处理参数，对图片依次进行缩放、旋转
            Map<String, Object> queryParams = new HashMap<String, Object>();
            queryParams.put("x-image-process", "image/resize,p_60");//长宽均压缩60%
            try {
                queryParams.put("x-image-save-object", ServiceUtils.toBase64(filename_short.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.setQueryParams(queryParams);
            // 生成临时授权URL
            TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
            //临时访问，生成缩略图（华为云在第一次访问该地址时才会生成实体文件）
            new WebRequest().doGet_simple(response.getSignedUrl());
        }
        return getFileUrl(filename_short);
    }

    public static void main(String agrs[]) {
        BucketFile bucketFile = new BucketFile("zjdm");
        System.err.println(bucketFile.getMinImageUrl("202105181621308129037B51e055c6.jpg"));

    }

    public ObjectMetadata getObjectMetadata(String objectname) {
        return obsClient.getObjectMetadata(bucketname, objectname);
    }

    /**
     * 关闭
     */
    public void close() {
        if (obsClient != null) {
            try {
                obsClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String getUploadUrl(String filetype, String objectname, HttpMethodEnum type) throws Exception {
        long expireSeconds = 3600L;
        Map<String, String> headers = new HashMap<String, String>();
        String contentType = "application/octet-stream";
        if (type.equals(HttpMethodEnum.POST)) {
            contentType = "multipart/form-data";
        }
        if ("pdf".equalsIgnoreCase(filetype)) {
            contentType = "application/pdf";
        }
        headers.put("Content-Type", contentType);

        TemporarySignatureRequest request = new TemporarySignatureRequest(type, expireSeconds);
        request.setBucketName(bucketname);
        request.setObjectKey(objectname);
        request.setHeaders(headers);

        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        return response.getSignedUrl();
    }


}
