package com.bonus.obs.utils;

import com.bonus.common.core.domain.R;
import com.bonus.obs.config.ObsConfig;
import com.obs.services.ObsClient;
import com.obs.services.model.DeleteObjectResult;
import com.obs.services.model.GetObjectRequest;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class ObsUtils {

    @Resource
    private ObsConfig obsConfig;
    /**
     * obs 客户端
     */
    private ObsClient obsClient;

    /**
     * 初始化信息
     * 构建OSS客户端实例
     */
    @PostConstruct
    public void init() {
        obsClient = new ObsClient(obsConfig.getAk(), obsConfig.getSk(), obsConfig.getEndpoint());
    }


    /**
     * 上传文件到OBS
     *
     * @param file 要上传的文件
     * @return 上传结果
     */
    public R<PutObjectResult> uploadFile(String objectKey, File file) {
        return R.ok(obsClient.putObject(obsConfig.getBucket(), objectKey, file));
    }

    /**
     * 下载文件从OBS
     *
     * @param objectKey 文件在OBS中的键
     */
    public R<ObsObject> downloadFile(String objectKey) {
        if (!doesObjectExist(objectKey)) {
            return R.fail("文件不存在");
        }
        return R.ok(obsClient.getObject(new GetObjectRequest(obsConfig.getBucket(), objectKey)));
    }

    /**
     * 删除文件从OBS
     *
     * @param objectKey 文件在OBS中的键
     */
    public R<DeleteObjectResult> deleteFile(String objectKey) {
        if (!doesObjectExist(objectKey)) {
            return R.fail("文件不存在");
        }
        return R.ok(obsClient.deleteObject(obsConfig.getBucket(), objectKey));
    }

    /**
     * 判断文件是否存在
     *
     * @param objectKey 文件在OBS中的键
     * @return 如果文件存在则返回true，否则返回false
     */
    public boolean doesObjectExist(String objectKey) {
        try {
            return obsClient.doesObjectExist(obsConfig.getBucket(), objectKey);
        } catch (Exception e) {
            return false;
        }
    }

}
