package shop.alien.util.command;

import lombok.extern.slf4j.Slf4j;
import shop.alien.util.random.RandomNumber;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 命令行工具类
 *
 * @author ssk
 * @version 1.0
 * @date 2024/12/24 10:13
 */
@Slf4j
public class CommandUtil {

    public static boolean test(String... a) {
        ProcessBuilder processBuilder = new ProcessBuilder();
        // 重定向错误流,防阻塞
        processBuilder.redirectErrorStream(true);
        processBuilder.command(a);
        try {
            Process process = processBuilder.start();
            // 获取流信息, 一般用于打印有返回值的例如:ipconfig
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            if (process.waitFor() == 0) {
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
        return false;
    }

    /**
     * ImageMagick图片格式转换
     *
     * @param imageFilePath 图片文件路径
     * @param convertType   转换格式
     * @return boolean
     */
    public static String imageConvert(String imageFilePath, String convertType) {
        log.info("CommandUtil.imageConvert imageFilePath={}, convertType={}", imageFilePath, convertType);
        imageFilePath = imageFilePath.replace("\\", "/");
        String[] pathList = imageFilePath.split("\\.");
        ProcessBuilder processBuilder = new ProcessBuilder();
        // 重定向错误流,防阻塞
        processBuilder.redirectErrorStream(true);
        String convertFile = pathList[0] + "." + convertType;
        // 如果转换文件存在,则重命名
        if (new File(convertFile).exists()) {
            convertFile = pathList[0] + "_" + RandomNumber.createRandom(1000, 9999) + "." + convertType;
        }
        processBuilder.command("magick", imageFilePath, convertFile);
        try {
            Process process = processBuilder.start();
            if (0 == process.waitFor()) {
                return convertFile;
            }
            return null;
        } catch (IOException | InterruptedException e) {
            log.error("CommandUtil.imageConvert ERROR Msg={}", e.getMessage());
            return null;
        }
    }

    /**
     * FFMpeg视频截取图片
     *
     * @param videoFilePath 视频媒体文件
     */
    public static String videoCaptureImage(String videoFilePath) {
        log.info("CommandUtil.videoCaptureImage videoFilePath={}", videoFilePath);
        String[] file = videoFilePath.split("\\.");
        // 截图保存位置
        String imgFilePath = file[0] + ".jpg";
        ProcessBuilder processBuilder = new ProcessBuilder();
        // 重定向错误流,防阻塞
        processBuilder.redirectErrorStream(true);
        // 调用ffmpeg 执行截取命令,需要服务器中安装了ffmpeg并配置了环境变量
        processBuilder.command("ffmpeg", "-i", videoFilePath, "-ss", "00:00:01", "-vframes", "1", imgFilePath);
        try {
            Process process = processBuilder.start();
            if (0 == process.waitFor()) {
                return imgFilePath;
            }
            return "";
        } catch (IOException | InterruptedException e) {
            log.error("CommandUtil.videoCaptureImage ERROR Msg={}", e.getMessage());
            return "";
        }
    }

    /**
     * FFMpeg视频截取图片
     *
     * @param videoFilePath 视频媒体文件
     */
    public static String getVideoTime(String videoFilePath) {
        log.info("CommandUtil.getVideoTime videoFilePath={}", videoFilePath);
        // 截图保存位置
        ProcessBuilder processBuilder = new ProcessBuilder();
        // 重定向错误流,防阻塞
        processBuilder.redirectErrorStream(true);
        // 调用ffmpeg 执行截取命令,需要服务器中安装了ffmpeg并配置了环境变量
        //ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 2497682.mp4
        processBuilder.command("ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", videoFilePath);
        try {
            Process process = processBuilder.start();
            // 获取流信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            String videoLength = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                videoLength = line;
            }
            if (0 == process.waitFor()) {
                return videoLength;
            }
            return "";
        } catch (IOException | InterruptedException e) {
            log.error("CommandUtil.captureImage ERROR Msg={}", e.getMessage());
            return "";
        }
    }
}
