package quant.rich.emoney.service.sqlite;

import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import quant.rich.emoney.entity.sqlite.ProxySetting;
import quant.rich.emoney.mapper.sqlite.ProxySettingMapper;
import quant.rich.emoney.pojo.dto.IpInfo;
import quant.rich.emoney.util.GeoIPUtil;

@DS("sqlite")
@Service
public class ProxySettingService extends SqliteServiceImpl<ProxySettingMapper, ProxySetting> {

    private volatile IpInfo ipInfo;
    
    /**
     * 获取默认代理配置
     * @return
     */
    public ProxySetting getDefaultProxySetting() {
        return getOne(
                new LambdaQueryWrapper<ProxySetting>()
                .eq(ProxySetting::getIsDefault, true));
    }
    
    /**
     * 获取默认代理配置的 IP 信息
     * @return
     */
    public IpInfo getDefaultProxySettingIpInfo() {
        ProxySetting proxySetting = getDefaultProxySetting();
        if (proxySetting == null) return null;
        if (ipInfo != null) return ipInfo;
        return refreshIpThroughProxy();
    }
    

    public synchronized IpInfo refreshIpThroughProxy() {
        ipInfo = GeoIPUtil.getIpInfoThroughProxy(getDefaultProxySetting());
        return ipInfo;
    }

    public void clearIpInfoCache() {
        ipInfo = null;
    }

}
