package tech.glinfo.enbao.modules.oss.cloud;

import com.qiniu.storage.BucketManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.glinfo.enbao.common.exception.RRException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

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

/**
 * 七牛云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class QiniuCloudStorageService extends CloudStorageService {
    private final static Logger logger = LoggerFactory.getLogger(QiniuCloudStorageService.class);
    private UploadManager uploadManager;
    private String token;
    private String key;

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

        //初始化
        init();
    }
    public QiniuCloudStorageService(CloudStorageConfig config, String key){
        this.config = config;
        this.key = key;
        //初始化
        init();
    }

    private void init(){
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()).
                uploadToken(config.getQiniuBucketName(), key, 3600L, StringUtils.isNotBlank(key) ? new StringMap().put("insertOnly", 0) : null);
    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path == null ? key : path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (Exception e) {
            throw new RRException("上传文件失败，请核对七牛配置信息", e);
        }

        return config.getQiniuDomain() + "/" + (path == null ? key : path);
    }

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

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

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

    @Override
    public Boolean delete(String fileName) {
        BucketManager bucketManager = new BucketManager(Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()), new Configuration(Zone.autoZone()));
        try {
            Response res = bucketManager.delete(config.getQiniuBucketName(), fileName);
            if (!res.isOK()) {
                logger.error("删除图片七牛出错：" + res.toString());
                return false;
            }
        } catch (Exception e) {
            logger.error("删除图片七牛出错", e);
            return false;
        }
        return true;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}
