package cn.reghao.tnb.gateway.lb;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @author reghao
 * @date 2023-02-03 16:24:31
 */
@Slf4j
public class UserLoadBalancer {
    private final DiscoveryClient discoveryClient;

    public UserLoadBalancer(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    /**
     * 根据 serviceId 筛选可用服务
     *
     * @param serviceId 服务ID
     * @param request   当前请求
     * @return
     */
    public ServiceInstance choose(String serviceId, ServerHttpRequest request) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        // 注册中心无实例 抛出异常
        if (instances == null || instances.isEmpty()) {
            log.warn("No instance available for {}", serviceId);
            throw new NotFoundException("No instance available for " + serviceId);
        }

        // 获取请求version，无则随机返回可用实例
        //String reqVersion = request.getHeaders().getFirst(CommonConstants.VERSION);
        int index = ThreadLocalRandom.current().nextInt(instances.size());
        ServiceInstance instance = instances.get(index);
        return instance;
    }
}
