package com.fs.system.oss;

import com.fs.common.exception.file.OssException;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectRequest;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import static com.fs.course.service.impl.HuaweiObsServiceImpl.generateUploadFileName;

/**
 * 腾讯云存储
 */
public class HuaweiCloudStorageService extends CloudStorageService
{
    private ObsClient client;

    public HuaweiCloudStorageService(CloudStorageConfig config)
    {
        this.config = config;
        // 初始化
        init();
    }

    private void init()
    {
        client = new ObsClient(config.getHuaweiAK(), config.getHuaweiSK(), config.getHuaweiEndpoint());
    }

    @Override
    public String upload(byte[] data, String path)
    {
        String objKey = generateUploadFileName(path);
        try {
            // 文件上传
            com.obs.services.model.PutObjectRequest request = new PutObjectRequest(config.getHuaweiBucketName(), objKey,new ByteArrayInputStream(data));
            client.putObject(request);
        } catch (ObsException e) {
            throw new ObsException("文件上传失败，" + e.getErrorMessage());
        } catch (Exception e) {
            System.out.println("上传失败");
            // 其他异常信息打印
            return "上传失败"+e.getMessage();
        }
        return config.getHuaweiDomain()+"/"+ objKey;

    }

    @Override
    public String upload(InputStream inputStream, String path)
    {
        try
        {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        }
        catch (IOException e)
        {
            throw new OssException("上传文件失败");
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix)
    {
        return upload(data, getPath(config.getQcloudPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix)
    {
        return upload(inputStream, getPath(config.getQcloudPrefix(), suffix));
    }
}
