package com.cftech.cos.alioss;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.cftech.cos.config.cosconfig.model.Cosconfig;
import com.cftech.cos.core.CosService;
import lombok.extern.slf4j.Slf4j;

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

/**
 * Created by liuling on 2017/5/2.
 */
@Slf4j
public class AliOssStorageService implements CosService {

    public static OSSClient getClient(Cosconfig cosconfig) {
        OSSClient client = new OSSClient(cosconfig.getEndpoint(), cosconfig.getKeyId(), cosconfig.getKeySecret());
        return client;
    }

    @Override
    public JSONObject uploadFile(Cosconfig cosconfig, byte[] data, String path) {
        return uploadFile(cosconfig, new ByteArrayInputStream(data), path);
    }

    @Override
    public JSONObject uploadFile(Cosconfig cosconfig, InputStream inputStream, String path) {
        JSONObject jsonObject = new JSONObject();
        if(path.startsWith("/")) {
            path = path.substring(1);
        }
        log.info("ready to uploadFile: {}", path);
        OSSClient client = getClient(cosconfig);
        try {
            client.putObject(cosconfig.getBucket(), path, inputStream);
            jsonObject.put("code", "0");
            log.info("uploadFile: {} success", path);
        } finally {
            client.shutdown();
        }
        return jsonObject;
    }


    @Override
    public JSONObject deleteFile(Cosconfig cosconfig, String path) {
        JSONObject jsonObject = new JSONObject();
        if(path.startsWith("/")) {
            path = path.substring(1);
        }
        log.info("ready to deleteFile : {}", path);
        OSSClient client = getClient(cosconfig);
        try {
            client.deleteObject(cosconfig.getBucket(), path);
            jsonObject.put("code", "0");
            log.info("delete File: {}, result: {}", path, "ok");
        } finally {
            client.shutdown();
        }
        return jsonObject;
    }
}
