package cd.casic.module.execute;

import cd.casic.module.execute.docker.dataobject.model.DockerEndpoint;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.util.StringUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import static java.lang.String.format;

/**
 * @description: TODO
 * @author: mianbin
 * @date: 2025/5/26 20:11
 * @version: 1.0
 */
@Slf4j
public class DockerPingServiceTest {
    private final Map<String, DockerClient> clientGroup = new ConcurrentHashMap<>();

    private ApacheDockerHttpClient createHttpClient(DockerEndpoint endpoint) {
        try {
            URI dockerHost;
            if (endpoint.getType() == DockerEndpoint.DockerEndpointTypeEnum.LOCAL) {
                // 使用本地挂载
                dockerHost = new URI("unix:///var/run/docker.sock");
            } else if (endpoint.getType() == DockerEndpoint.DockerEndpointTypeEnum.REMOTE) {
                // 远程挂载
                dockerHost = new URI(format("tcp://%s:%s", endpoint.getHost(), endpoint.getPort()));
            } else {
                log.error("Unsupported Docker endpoint type: {}", endpoint.getType());
                return null;
            }
            return new ApacheDockerHttpClient.Builder()
                    .dockerHost(dockerHost)
                    .build();
        } catch (URISyntaxException e) {
            log.error("Failed to create URI for Docker endpoint {}: {}", endpoint.getId(), e.getMessage(), e);
            return null;
        }
    }

    @BeforeEach
    public void setUp() {
        DockerEndpoint endpoint = new DockerEndpoint();
        endpoint.setId("158");
        endpoint.setType(DockerEndpoint.DockerEndpointTypeEnum.REMOTE);
        endpoint.setHost("175.6.27.158");
        endpoint.setPort(22375);
        endpoint.setName("test");
        ApacheDockerHttpClient httpClient = createHttpClient(endpoint);
        DockerClient dockerClient = DockerClientBuilder.getInstance().withDockerHttpClient(httpClient).build();
        clientGroup.put(endpoint.getId(), dockerClient);
    }

    @Test
    public void ping(){
        String clientId = "158";
        DockerClient dockerClient = Optional.of(StringUtils.hasText(clientId) ? clientId : "DEFAULT")
                .map(id -> id.toUpperCase(Locale.ROOT))
                .map(t->clientGroup.get("158"))
                .orElseThrow(() -> new RuntimeException("客户端不存在"));
        dockerClient.pingCmd().exec();
    }

}
