package com.microservices.pms.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author OTTO
 * python执行工具类
 */
public class PythonUtil {
    private static final Logger log = LoggerFactory.getLogger(NexusRequestHelper.class);

    /**
     * 拉取docker镜像
     * PythonUtil.pullDockerImage("172.20.32.201:31111/mysql:5.7","mysql_5.7.tar")
     *
     * @param dockerImgUrl      docker镜像地址
     * @param dockerImgFileName docker镜像包文件名
     * @return 文件字节数组
     */
    public static InputStream pullDockerImage(String dockerImgUrl, String dockerImgFileName) throws IOException {

        InputStream inputStream = PythonUtil.class.getClassLoader().getResourceAsStream("scripts/docker_pull.py");
        Path tempDirPath = Files.createTempDirectory("py_docker_pull");
        // 创建临时文件
        Path tempFilePath = Files.createTempFile(tempDirPath, "docker_pull", ".py");
        File somethingFile = tempFilePath.toFile();
        String filePath;
        String command = null;
        try {
            if (inputStream != null) {
                FileUtils.copyInputStreamToFile(inputStream, somethingFile);
            }
            filePath = somethingFile.getAbsolutePath();
            log.info("文件路径:{}", filePath);

            Runtime runTime = Runtime.getRuntime();
            command = "python3 " + filePath;
            command += " " + dockerImgUrl;

            command += " " + tempDirPath + " " + dockerImgFileName;
            log.info("执行脚本[{}]", command);

            Process proc = runTime.exec(command);
            BufferedReader bfr = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;
            while ((line = bfr.readLine()) != null) {
                log.info(line);
            }
            proc.waitFor();
            File file = tempDirPath.resolve(dockerImgFileName).toFile();
            return Files.newInputStream(file.toPath());

        } catch (Exception e) {
            log.error("脚本[{}]执行失败:{}", command, e.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
            //删除临时文件
            File dir = tempDirPath.toFile();
            File[] fileList = dir.listFiles();
            boolean isDeleteSuccess = true;
            if (fileList != null) {
                for (File file : fileList) {
                    boolean deleteResult = file.delete();
                    if (!deleteResult) {
                        isDeleteSuccess = false;
                    }
                }
            }
            //删除临时目录
            if (isDeleteSuccess) {
                Files.delete(tempDirPath);
            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        InputStream fileBytes = PythonUtil.pullDockerImage("172.20.32.201:31111/aaa/bbb/ccc:5.0", "aaa_bbb_ccc_5.0.tar");
        Assert.notNull(fileBytes, "通过Python拉取Docker镜像失败!");
    }
}
