package cn.reghao.devops.web.devops;

import cn.reghao.devops.common.docker.Docker;
import cn.reghao.devops.common.docker.DockerImpl;
import cn.reghao.devops.common.docker.po.ContainerInfo;
import cn.reghao.devops.common.docker.po.ImageInfo;
import cn.reghao.jutil.jdk.thread.ThreadPoolWrapper;
import org.junit.Test;

import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2022-05-07 09:32:40
 */
public class DockerTest {
    @Test
    public void dockerListTest() {
        Pattern pattern = Pattern.compile("^\\S*$");
        String str = "dfa   safd";
        String str1 = "dfasafd";
        boolean matched = pattern.matcher(str).matches();
        System.out.println();
    }

    @Test
    public void dockerBuildTest() throws Exception {
        DockerImpl docker = new DockerImpl();
        String repoTag = "file:12345678";
        String compileHome = "/home/reghao/code/aha/tnb/file/file-service";
        docker.build(repoTag, compileHome);
    }

    @Test
    public void dockerTest() {
        DockerImpl docker = new DockerImpl();

        Map<String, ImageInfo> map = docker.images().stream().collect(Collectors.toMap(ImageInfo::getImageId, info -> info));
        List<ContainerInfo> containerInfos = docker.psAll();
        for (ContainerInfo containerInfo : containerInfos) {
            String imageId = containerInfo.getImageId();
            ImageInfo imageInfo = map.remove(imageId);
        }
        //map.keySet().forEach(docker::imageRm);

        ImageCleanTask cleanTask = new ImageCleanTask(docker);
        ScheduledExecutorService threadPool = ThreadPoolWrapper.scheduledThreadPool("image-cleaner", 1);
        threadPool.scheduleAtFixedRate(cleanTask, 1, 12, TimeUnit.HOURS);
    }

    class ImageCleanTask implements Runnable {
        private Docker docker;

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

        @Override
        public void run() {
            Map<String, ImageInfo> map = docker.images().stream().collect(Collectors.toMap(ImageInfo::getImageId, info -> info));
            List<ContainerInfo> containerInfos = docker.psAll();
            for (ContainerInfo containerInfo : containerInfos) {
                String imageId = containerInfo.getImageId();
                ImageInfo imageInfo = map.remove(imageId);
            }

            //map.keySet().forEach(docker::imageRm);
        }
    }
}
