package cn.reghao.bnt.agent.task;

import cn.reghao.bnt.common.docker.Docker;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Image;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2024-07-29 16:17:47
 */
@Slf4j
public class ImageCleanTask implements Runnable {
    private final Docker docker;

    public ImageCleanTask(Docker docker) {
        this.docker = docker;
    }

    @Override
    public void run() {
        Map<String, Image> map = docker.images().stream()
                .collect(Collectors.toMap(Image::getId, image -> image));

        List<InspectContainerResponse> list = docker.psAll();
        for (InspectContainerResponse response : list) {
            String imageId = response.getImageId();
            Boolean running = response.getState().getRunning();
            if (running != null && running) {
                Image image = map.remove(imageId);
            }
        }

        //map.keySet().forEach(docker::imageRm);
        log.info("定时扫描 docker 镜像和容器");
    }
}
