package cn.bunny.video.utils;


import lombok.extern.slf4j.Slf4j;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.*;
import java.util.List;

@Slf4j
public class SystemControlUtils {

    /**
     * 播放音乐
     */
    public static void playMusic() {
        ClassLoader classLoader = SystemControlUtils.class.getClassLoader();
        try (InputStream inputStream = classLoader.getResourceAsStream("static/download-complete/download-complete.wav")) {
            if (inputStream == null) {
                log.warn("无法找到音乐文件！");
                return;
            }

            try (Clip clip = AudioSystem.getClip()) {
                clip.open(AudioSystem.getAudioInputStream(inputStream));
                clip.start();

                // 等待音乐播放完成
                Thread.sleep(clip.getMicrosecondLength() / 1000);
            } catch (Exception e) {
                log.error("播放音乐时发生错误", e);
                throw new RuntimeException("播放音乐时发生错误", e);
            }

        } catch (IOException e) {
            log.error("加载音乐文件失败", e);
            throw new RuntimeException("加载音乐文件失败", e);
        }
    }

    /**
     * 执行命令行并输出（带有当前下载索引）
     *
     * @param command      命令内容
     * @param currentIndex 当前下载的第几个
     */
    public static void startProcess(List<String> command, int currentIndex) {
        startProcess(command, currentIndex, "D:\\software\\Plugins\\Mu3U8下载\\");
    }

    /**
     * 执行命令行并输出
     *
     * @param command 命令内容
     */
    public static void startProcess(List<String> command) {
        startProcess(command, -1, "D:\\software\\Plugins\\Mu3U8下载\\");
    }

    /**
     * 执行命令行并输出（抽象出的公共逻辑）
     *
     * @param command      命令内容
     * @param currentIndex 当前下载的第几个（可选）
     * @param workDir      工作目录
     */
    private static void startProcess(List<String> command, int currentIndex, String workDir) {
        try {
            // 创建进程构建器
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.directory(new File(workDir));

            // 启动进程
            Process process = processBuilder.start();

            // 读取命令输出，指定使用 GBK 编码
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (currentIndex != -1) {
                        log.info("第 {} 个下载任务输出: {}", currentIndex, line);
                    } else {
                        log.info(line);
                    }
                }
            }

            // 等待命令执行完成
            int exitCode = process.waitFor();
            if (currentIndex != -1) {
                log.info("第 {} 个任务执行完毕，退出码: {}", currentIndex, exitCode);
            } else {
                log.info("命令执行完毕，退出码: {}", exitCode);
            }

        } catch (IOException | InterruptedException e) {
            log.error("执行命令时发生错误", e);
            throw new RuntimeException("执行命令时发生错误", e);
        }
    }
}
