package com.qmth.boot.core.fss.store.impl;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.qmth.boot.core.fss.store.FileStore;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.io.InputStream;
import java.time.Duration;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

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

    private static final String ENDPOINT_PREFIX_HTTP = "http://";

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

    private String server;

    private String bucket;

    private OSS ossClient;

    private OSS temporaryUrlClient;

    public OssStore(String server, String config) {
        String message = "fss.config: " + 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));
            this.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);

            this.server = server;
            //判断是否阿里云OSS地址还是私服，使用不同的前缀
            if (endpoint.contains("aliyun")) {
                endpoint = ENDPOINT_PREFIX_HTTPS.concat(endpoint);
            } else {
                endpoint = ENDPOINT_PREFIX_HTTP.concat(endpoint);
            }
            this.ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessSecret);
            //为支持私有读的bucket，构造专门用于获取临时访问URL的client
            ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
            conf.setSupportCname(true);
            this.temporaryUrlClient = new OSSClientBuilder().build(server, accessKey, accessSecret, conf);
        } else {
            throw new IllegalArgumentException(message);
        }
    }

    @Override
    public String getServer() {
        return server;
    }

    @Override
    public String getPresignedUrl(String path, Duration expireDuration) {
        return temporaryUrlClient.generatePresignedUrl(bucket, formatPath(path),
                new Date(System.currentTimeMillis() + expireDuration.toMillis())).toString();
    }

    @Override
    public void write(String path, InputStream ins, String md5) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentMD5(toBase64(md5));
        ossClient.putObject(bucket, formatPath(path), ins, metadata);
    }

    @Override
    public InputStream read(String path) {
        OSSObject ossObject = ossClient.getObject(bucket, formatPath(path));
        return ossObject.getObjectContent();
    }

    @Override
    public boolean exist(String path) {
        try {
            return ossClient.doesObjectExist(bucket, formatPath(path));
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean delete(String path) {
        ossClient.deleteObject(bucket, formatPath(path));
        return true;
    }

    @Override
    public void copy(String source, String target) throws Exception {
        ossClient.copyObject(bucket, formatPath(source), bucket, formatPath(target));
    }

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

}
