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

import com.zhili.stationcontrol.tts.service.MusicService;
import com.zhili.stationcontrol.tts.util.WavPlayUtil;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;

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

    @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;
        }
    }

    @Scheduled(fixedRate = 500)
    public void play() {
        synchronized (this) {
            log.info("startCmd:{}, endCmd:{}, repeat:{}", startCmd, endCmd, repeat);
            log.info("p:{}, p.isAlive:{}", p, p != null ? p.isAlive() : null);
            if (startCmd) {
                startCmd = false;
                if (p != null) {
                    p.destroyForcibly();
                    p = null;
                }
                try {
                    p = Runtime.getRuntime().exec(cmd);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (endCmd) {
                endCmd = false;
                if (p != null) {
                    p.destroyForcibly();
                    p = null;
                }
            }
            if (!startCmd && !endCmd && repeat && p == null && cmd != null) {
                log.info("repeat:{}", cmd);
                try {
                    p = Runtime.getRuntime().exec(cmd);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        System.out.println(Float.valueOf(new Integer(2).toString()) / 10);
    }
}
