package com.lanyuanxiaoyao.service.forest.configuration;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.dtflys.forest.auth.BasicAuth;
import com.dtflys.forest.http.ForestAddress;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import java.net.URL;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

/**
 * @author lanyuanxiaoyao
 * @date 2023-04-24
 */
@Component
public class SpringCloudDiscoveryInterceptor implements Interceptor<Object> {
    private static final Logger logger = LoggerFactory.getLogger(SpringCloudDiscoveryInterceptor.class);

    private final DiscoveryClient client;

    public SpringCloudDiscoveryInterceptor(DiscoveryClient client) {
        this.client = client;
    }

    @Override
    public boolean beforeExecute(ForestRequest request) {
        // Load
        URL url = URLUtil.url(request.getUrl());
        String host = url.getHost();
        if (StrUtil.isNotBlank(host)) {
            ImmutableList<ServiceInstance> instances = Lists.immutable.ofAll(client.getInstances(host));
            if (ObjectUtil.isNotEmpty(instances)) {
                int index = RandomUtil.randomInt(instances.size());
                ServiceInstance instance = instances.get(index);
                request.setAddress(new ForestAddress(instance.getScheme(), instance.getHost(), instance.getPort()));
            }
        }

        // Basic auth
        BasicAuth basicAuth = new BasicAuth("AxhEbscwsJDbYMH2", "cYxg3b4PtWoVD5SjFayWxtnSVsjzRsg4");
        basicAuth.enhanceAuthorization(request);

        return Interceptor.super.beforeExecute(request);
    }
}
