package cd.casic.module.execute;

import cd.casic.module.execute.docker.dataobject.model.DockerEndpoint;
import cn.hutool.core.io.FileUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.model.Image;
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 java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
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 ImageServiceTest {
    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 listTest() {
        DockerClient dockerClient = clientGroup.get("158");
        List<Image> exec = dockerClient.listImagesCmd().exec();
        System.out.println(exec);
    }

    @Test
    public void inspect() {
        DockerClient dockerClient = clientGroup.get("158");
        InspectImageResponse exec = dockerClient
                .inspectImageCmd("5a9e3ee3b8c1be74f5f89b092aea791d3ca058054ec0f3522b79d9985eff3087").exec();
        System.out.println(exec);
    }

    @Test
    public void tag() {
        /* 测试的hallo-world */
        String imagesId = "74cc54e27dc4";
        DockerClient dockerClient = clientGroup.get("158");
        InspectImageResponse inspect = dockerClient
                .inspectImageCmd(imagesId).exec();
        if (inspect == null) {
            throw new RuntimeException("操作失败，镜像不存在");
        }
        dockerClient.tagImageCmd(imagesId, inspect.getRepoTags().get(0), "hallo-newworld1").exec();
    }

    @Test
    public void remove() {
        String imageId = "be69f2940aaf";
        DockerClient dockerClient = clientGroup.get("158");
        dockerClient.removeImageCmd(imageId).withForce(true).exec();
    }

    /*todo local 模式生效*/
    @Test
    public void importByTar() {
        DockerClient dockerClient = clientGroup.get("158");
        File file = new File("/home/ubuntu/nginx.tar");
        Void exec = dockerClient.loadImageCmd(FileUtil.getInputStream(file)).exec();
    }

    @Test
    public void exist() {
        String imageId = "be69f2940aaf";
        DockerClient dockerClient = clientGroup.get("158");
        System.out.println(dockerClient.inspectImageCmd(imageId).exec() != null);
    }

    @Test
    public void pushImage() {
        String imageId = "be69f2940aaf";
        DockerClient dockerClient = clientGroup.get("158");
        try {
            dockerClient.pushImageCmd(imageId).exec(null);
            log.info("推送镜像成功: ");
        } catch (Exception e) {
            log.error("推送镜像失败: " + e.getMessage());
        }
    }

}
