package link.at17.mid.tushare.system.config;

import java.net.InetSocketAddress;
import java.net.Proxy;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;

import com.fasterxml.jackson.annotation.JsonIgnore;

import link.at17.mid.tushare.annotation.ConfigInfo;
import link.at17.mid.tushare.annotation.StaticAttribute;
import link.at17.mid.tushare.interfaces.IConfig;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@ConfigInfo(field = "system", name = "平台设置", initDefault = true)
@Lazy(false)
public class SystemConfig implements IConfig<SystemConfig> {

    private String tushareToken;
    
    @StaticAttribute("ProxyTypeEnum")
    private Proxy.Type proxyType = Proxy.Type.DIRECT;
    
    private String proxyHost = "";
    
    private Integer proxyPort = 1;
    
    private Boolean ignoreHttpsVerification = false;

    
    public SystemConfig() {
        tushareToken = "";
    }

    /**
     * 根据配置获取代理
     * @return
     */
    @JsonIgnore
    public Proxy getProxy () {
        if (getProxyType() != null && getProxyType() != Proxy.Type.DIRECT) {
            return new Proxy(getProxyType(), 
                    new InetSocketAddress(getProxyHost(), getProxyPort()));
        }
        return Proxy.NO_PROXY;
    }
    
    /**
     * 根据配置获取代理 Url
     * @return
     */
    public String getProxyUrl() {
        if (ObjectUtils.anyNull(getProxyType(), getProxyHost(), getProxyPort())) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        if (getProxyType() == Proxy.Type.SOCKS) {
            sb.append("socks5://");
        }
        else if (getProxyType() == Proxy.Type.HTTP) {
            sb.append("http://");
        }
        else {
            return null;
        }
        sb.append(getProxyHost()).append(':').append(getProxyPort());
        return sb.toString();
    }

}
