/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.dianguang.cloud.ossservice.service;

import com.dianguang.cloud.ossservice.config.CloudStorageConfig;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;

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

/**
 * 七牛云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class QiniuCloudStorageService extends AbstractCloudStorageService {
    private UploadManager uploadManager;
    private String token;

    public QiniuCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
        token = Auth.create(config.getAccessKey(), config.getSecretKey()).
                uploadToken(config.getBucketName());

    }

    @Override
    public String upload(byte[] data, String path) throws Exception {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new Exception("上传失败");
            }
        } catch (Exception e) {
            throw new Exception("上传失败");
        }

        return config.getUrl() + "/" + path;
    }

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

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

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

    @Override
    public String uploadFileName(byte[] data, String suffix,String fileName) throws Exception {
        return upload(data, getPath(config.getPrefix(), suffix,fileName));
    }
}
