package com.lanyuanxiaoyao.service.web.controller;

import com.lanyuanxiaoyao.service.configuration.entity.AmisResponse;
import com.lanyuanxiaoyao.service.web.entity.CloudServiceVO;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.list.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 云页面
 *
 * @author lanyuanxiaoyao
 * @date 2023-04-30
 */
@RestController
@RequestMapping("cloud")
public class CloudController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CloudController.class);

    private final DiscoveryClient client;

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

    @GetMapping("list")
    public AmisResponse list() {
        ImmutableList<CloudServiceVO> serviceVOS = Lists.immutable.ofAll(client.getServices())
                .collect(name -> {
                    ImmutableList<CloudServiceVO.Service> instances = Lists.immutable.ofAll(client.getInstances(name))
                            .collect(instance -> new CloudServiceVO.Service(
                                    instance.getInstanceId(),
                                    instance.getServiceId(),
                                    instance.getHost(),
                                    instance.getPort(),
                                    instance.isSecure(),
                                    instance.getUri().toString(),
                                    Maps.immutable.ofAll(instance.getMetadata())
                            ));
                    return new CloudServiceVO(name, instances);
                });
        return responseCrudData(serviceVOS, serviceVOS.size());
    }
}
