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 javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author ：HuangBin
 * @description：TODO
 * @date ：2023/6/6 17:08
 */
@Service
@Slf4j
@EnableScheduling
public class MusicServiceImpl implements MusicService, Runnable {
    Process p;
    String cmd;
    //1:开始命令到达，0：无开始命令
    Boolean startCmd = false;
    //1:结束命令到达，0：无结束命令
    Boolean endCmd = false;
    //1:重复播放，0：不重复
    Boolean repeat = false;

    Thread thread;

    @PostConstruct
    public void init(){
        this.thread = new Thread(this);
        this.thread.start();
    }

    @Override
    public Integer start(String path, Integer vol) {
        synchronized (this) {
            cmd = "play -v " + Float.valueOf(new Integer(vol).toString()) / 100 + " " + path;
            log.info("start music cmd:{}", cmd);
            startCmd = true;
            repeat = true;
            return 0;
        }
    }

    @Override
    public void stop() {
        synchronized (this) {
            log.info("stop music");
            endCmd = true;
            repeat = false;
        }
    }


    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
                log.info("----------");
                log.info("startCmd:{},endCmd:{},repeat:{},cmd:{}", startCmd, endCmd, repeat, cmd);
                log.info("p:{},p.isAlive:{}", p, p == null ? null : p.isAlive());
                if (startCmd) {
                    startCmd = false;
                    if (p != null) {
                        p.destroyForcibly();
                        p.waitFor();
                        p = null;
                    }
                    p = Runtime.getRuntime().exec(cmd);
                }
                if (endCmd) {
                    endCmd = false;
                    if (p != null) {
                        p.destroyForcibly();
                        p.waitFor();
                        p = null;
                    }
                }
                if (!startCmd && !endCmd && repeat && cmd != null) {
                    if (p != null) {
                        boolean exit = p.waitFor(500, TimeUnit.MILLISECONDS);
                        if (exit) {
                            log.info("repeat");
                            p = Runtime.getRuntime().exec(cmd);
                        } else {
                            return;
                        }
                    } else {
                        p = Runtime.getRuntime().exec(cmd);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
