package com.zhili.stationcontrol.tts.service.impl;

import com.zhili.stationcontrol.tts.service.MusicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import static java.lang.System.out;

/**
 * @author ：HuangBin
 * @description：TODO
 * @date ：2023/6/6 17:08
 */
@Service
@Slf4j
@EnableScheduling
public class MusicServiceImpl implements MusicService {
    Process p;


    @Override
    public Integer start(String path, Integer vol) {
        synchronized (this) {
            try {
                String cmd = "play -v " + Float.valueOf(new Integer(vol).toString()) / 100 + " " + path + " repeat 10000";
                log.info("start music cmd:{}", cmd);
                if (p != null) {
                    p.destroyForcibly();
                    p.waitFor();
                    p = null;
                }
                p = Runtime.getRuntime().exec(cmd);
                inputProcess(p.getInputStream(), "inputStream");
                inputProcess(p.getErrorStream(), "errorStream");
                return 0;
            } catch (Exception e) {
                e.printStackTrace();
                return 1;
            }
        }
    }

    @Override
    public void stop() {
        synchronized (this) {
            try {
                log.info("stop music");
                if (p != null) {
                    p.destroyForcibly();
                    p.waitFor();
                    p = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    void inputProcess(final InputStream in, String name) {
        //必须是新线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (in == null) return;
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        if (line != null) {
                            out.println(line);
                        }
                    }
                } catch (Exception e) {

                } finally {
                    try {
                        if (in != null) in.close();
                    } catch (Exception ec) {

                    }
                }
            }
        }, name).start();
    }
}
