package com.fdkankan.filestorage.properties;


import com.aliyun.oss.ClientBuilderConfiguration;
import com.fdkankan.filestorage.InnerUtils;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Map;

/**
 * 阿里云OSS配置属性
 */
@Data
@ConfigurationProperties(prefix = "filestorage.oss")
public class AliyunOssProperties implements Serializable, InitializingBean {

    public static final String PREFIX = "filestorage.oss";

    private String active;
    /**
     * 服务地址
     */
    private String endpoint;

    /**
     * 服务地址(内网)
     */
    private String internalEndpoint;

    /**
     * 区域id
     */
    private String regionId;

    /**
     * 访问标识
     */
    private String accessKey;

    /**
     * 访问密钥
     */
    private String accessKeySecret;

    /**
     * 自定义域名, bucket名称忽略大小写
     */
    private Map<String, String> bucketCustomDomain;

    /**
     * Bucket
     */
    private String bucket;
    /**
     * Client configuration.
     */
    private ClientBuilderConfiguration config = new ClientBuilderConfiguration();
    /**
     * return fullPath
     */
    private boolean fullPath =true;

    @Override
    public void afterPropertiesSet() {
        InnerUtils.checkArgument(!StringUtils.isEmpty(endpoint), "'endpoint' can't be empty");
        InnerUtils.checkArgument(!StringUtils.isEmpty(bucket), "'bucket' can't be empty");
    }

    /**
     * 获取请求到阿里云的服务地址, 内网地址优先
     */
    public String getRequestEndpoint() {
        if (this.internalEndpoint != null && this.internalEndpoint.length() > 0) {
            return internalEndpoint;
        }
        return endpoint;
    }

    /**
     * 获取访问访问前缀, 优先级: customDomain > endpoint
     */
    public String getHostByBucket(String bucket) {
        if (bucketCustomDomain != null) {
            String domain = bucketCustomDomain.get(bucket);
            if (domain != null && domain.length() > 0) {
                return domain;
            }
        }
        return InnerUtils.generateHost(this.endpoint, bucket);
    }
}
