package cn.com.qmth.stmms.biz.file.store.impl;

import cn.com.qmth.stmms.biz.file.store.FileStore;
import cn.com.qmth.stmms.common.utils.Encodes;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * OSS文件管理工具
 */
public class OssStore implements FileStore {

    private static final Logger log = LoggerFactory.getLogger(OssStore.class);

    private static final String ENDPOINT_PREFIX = "https://";

    private static final Pattern CONFIG_PATTERN = Pattern.compile("^oss://([\\w]+):([\\w]+)@([\\w-]+).([\\w-.]+)$");

    private OSS ossClient;

    private String bucket;

    public OssStore(String config) {
        String message = "[file.store]" + config + ": pattern error";
        Matcher m = CONFIG_PATTERN.matcher(config);
        if (m.find()) {
            String accessKey = StringUtils.trimToNull(m.group(1));
            String accessSecret = StringUtils.trimToNull(m.group(2));
            bucket = StringUtils.trimToNull(m.group(3));
            String endpoint = StringUtils.trimToNull(m.group(4));

            Assert.notNull(accessKey, message);
            Assert.notNull(accessSecret, message);
            Assert.notNull(bucket, message);
            Assert.notNull(endpoint, message);

            ossClient = new OSSClientBuilder().build(ENDPOINT_PREFIX.concat(endpoint), accessKey, accessSecret);
        } else {
            throw new IllegalArgumentException(message);
        }
    }

    @Override
    public void write(String path, InputStream ins, String md5) throws Exception {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentMD5(BinaryUtil.toBase64String(Encodes.decodeHex(md5)));
        // 设置内容被下载时网页的缓存行为。
        metadata.setCacheControl("no-cache");
        ossClient.putObject(bucket, path, ins, metadata);
    }

    @Override
    public byte[] read(String path) throws Exception {
        OSSObject ossObject = ossClient.getObject(bucket, path);
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        IOUtils.copy(ossObject.getObjectContent(), ous);
        ossObject.close();
        return ous.toByteArray();
    }

    @Override
    public boolean exist(String path) {
        try {
            return ossClient.doesObjectExist(bucket, path);
        } catch (Exception e) {
            log.error("oss exist operate error", e);
            return false;
        }
    }

    @Override
    public void close() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}
