package cd.casic.ci.process.process.service.docker.impl;

import cd.casic.ci.process.dto.req.resource.ResourceQueryReq;
import cd.casic.ci.process.dto.resp.resource.ResourceDetailResp;
import cd.casic.ci.process.process.service.docker.DockerService;
import cd.casic.ci.process.process.service.resource.ResourceManagerService;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.module.execute.docker.dataobject.dto.DockerEndpointDo;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import jakarta.annotation.Resource;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static java.lang.String.format;
@Service
public class DockerServiceImpl implements DockerService {
    @Resource
    private ResourceManagerService resourceManagerService;
    @Override
    public List<String> imageListByResourceId(String resourceId) {
        ResourceDetailResp resourceById = resourceManagerService.findResourceDetailById(resourceId);
        DockerEndpointDo dockerInfo = resourceById.getDockerInfo();
        URI uri = null;
        try {
            uri = new URI(format("tcp://%s:%s", dockerInfo.getHost(), dockerInfo.getPort()));
        } catch (URISyntaxException e) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR);
        }

        ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder().dockerHost(uri).build();
        DockerClient build = null;
        try{
            build = DockerClientBuilder.getInstance().withDockerHttpClient(httpClient).build();
            List<Image> exec = build.listImagesCmd().exec();
            List<String> res = new LinkedList<>();
            for (Image image : exec) {
                String[] repoTags = image.getRepoTags();
                if (image.getRepoTags() != null && repoTags.length > 0) {
                    res.add(repoTags[0]);
                }
            }
            return res;
        } finally {
            if (build!=null) {
                try {
                    build.close();
                } catch (IOException e) {

                }
            }
        }
    }
}
