package com.qmth.boot.core.fss.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OssConfig {

    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-.]+)$");

    private static final Pattern ALIYUN_HOST_PATTERN = Pattern
            .compile("^([\\w-]+).oss-(cn-[a-z]+)(-internal)?.aliyuncs.com$");

    private static final Pattern OTHER_HOST_PATTERN = Pattern.compile("^([\\w-]+).([\\w-.]+)$");

    private String endpoint;

    private String host;

    private String region;

    private String bucket;

    private String accessKey;

    private String accessSecret;

    private String portal;

    private String portalHost;

    public OssConfig(String config, String server) {
        String message = "fss.config: " + config + ": pattern error";
        Matcher m = CONFIG_PATTERN.matcher(config);
        if (m.find()) {
            this.portal = server;
            this.portalHost = getHost(portal);
            this.accessKey = StringUtils.trimToNull(m.group(1));
            this.accessSecret = StringUtils.trimToNull(m.group(2));
            this.host = StringUtils.trimToNull(m.group(3));

            Assert.notNull(accessKey, message);
            Assert.notNull(accessSecret, message);
            Assert.notNull(host, message);

            m = ALIYUN_HOST_PATTERN.matcher(this.host);
            if (m.find()) {
                this.bucket = m.group(1);
                this.region = m.group(2);
                this.endpoint = ENDPOINT_PREFIX_HTTPS + this.host;
            } else {
                m = OTHER_HOST_PATTERN.matcher(this.host);
                if (m.find()) {
                    this.bucket = m.group(1);
                } else {
                    this.bucket = "";
                }
                this.region = "";
                this.endpoint = ENDPOINT_PREFIX_HTTP + this.host;
            }
        } else {
            throw new IllegalArgumentException(message);
        }
    }

    public String getEndpoint() {
        return endpoint;
    }

    public String getHost() {
        return host;
    }

    public String getRegion() {
        return region;
    }

    public String getBucket() {
        return bucket;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public String getAccessSecret() {
        return accessSecret;
    }

    public String getPortal() {
        return portal;
    }

    public String getPortalHost() {
        return portalHost;
    }

    private String getHost(String url) {
        try {
            return new URL(url).getHost();
        } catch (Exception e) {
            return "";
        }
    }
}
