package com.hfkj.obs;

import com.hfkj.config.CommonSysConfig;
import com.hfkj.config.CommonSysConst;
import com.obs.services.ObsClient;
import com.obs.services.model.*;

import java.io.File;

/**
 * 华为云obs 对象存储
 * @author hurui
 */
public class HuaWeiYunObs {

    public static String url = CommonSysConst.getSysConfig().getObs_url();
    private static String endPoint = CommonSysConst.getSysConfig().getObs_end_point();
    private static String accessKey = "CZVO7VAT8UV2RPYJUBD2";
    private static String secretKey = "gyjrR8rYq9w2maPq9VmpRqoMqCJzQMH8vMctg7eE";

    /**
     * 创建请求
     * @return
     */
    private static ObsClient createClient() {
        return new ObsClient(accessKey, secretKey, endPoint);
    }

    /**
     * 关闭请求
     * @param obsClient
     */
    private static void closeClient(ObsClient obsClient) {
        try {
            if (obsClient != null) {
                obsClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     * @param bucketName 桶名称
     * @param objectName 对象名称  例如：1.jpg
     * @param file 文件路径
     * @return
     */
    public static PutObjectResult putObject(String bucketName,String objectName, File file) {
        ObsClient client = createClient();
        try {
            return client.putObject(bucketName, objectName, file);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeClient(client);
        }
        return null;
    }

    /**
     * 获取图片临时路径
     * @param bucketName 桶名称
     * @param objectName 对象名称  例如：1.jpg
     * @return
     */
    public static String getImgSignedUrl(String bucketName,String objectName) {
        ObsClient client = createClient();
        try {
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 1800L);
            request.setBucketName(bucketName);
            request.setObjectKey(objectName);

            TemporarySignatureResponse response = client.createTemporarySignature(request);
            return response.getSignedUrl();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeClient(client);
        }
        return null;
    }


}
