package com.zhili.stationcontrol.tts.controller;

import com.zhili.stationcontrol.tts.service.MusicService;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author ：HuangBin
 * @description：TODO
 * @date ：2023/5/17 22:56
 */
@RestController
@Slf4j
public class TtsController {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MusicService musicService;

    @Value("${play_path:/static/wav/music.mp3}")
    String playPath;

//    @GetMapping("/speak/{txt}")
//    public String speak(@PathVariable String txt) {
////        redisTemplate.opsForList().rightPush("ttsList", txt);
//        speak(txt,100);
//        return txt;
//    }
//
//    @GetMapping("/speak1/{txt}/{vol}")
//    public String speak(@PathVariable String txt,@PathVariable Integer vol) {
//        vol = vol > 1000 ? 1000 : vol;
//        vol = vol < 0 ? 0 : vol;
//        Map<String,Object> m = new HashMap();
//        m.put("txt",txt);
//        m.put("vol",vol);
//        redisTemplate.opsForList().rightPush("ttsList", JSON.toJSONString(m));
//        return txt;
//    }
//
//    @GetMapping("/speakFile/{fileName}")
//    public String speakFile(@PathVariable String fileName) {
//        String path = "/home/" + fileName + ".wav";
//        log.info("path:{}", path);
//        WavPlayUtil.play(path);
//        return fileName;
//    }
//
//    @GetMapping("/speakFile1/{fileName}")
//    public String speakFile1(@PathVariable String fileName) throws IOException, InterruptedException {
//        String path = "/home/" + fileName + ".wav";
//        log.info("path:{}", path);
//        Process exec = Runtime.getRuntime().exec("play " + path);
//        exec.waitFor();
//        return path;
//    }

    @GetMapping("/startMusic/{vol}")
    public String startMusic(@PathVariable Integer vol) {
        vol = vol > 1000 ? 1000 : vol;
        vol = vol < 0 ? 0 : vol;
        //log.info("start music with vol:{}", vol);
        Integer start = musicService.start(playPath, vol);
        return start.equals(0) ? "ok" : "error";
    }

    @GetMapping("/stopMusic")
    public String stopMusic() {
        log.info("stop music");
        musicService.stop();
        return "ok";
    }

    @GetMapping("/speak/{file}")
    public String speak(@PathVariable String file) throws IOException, InterruptedException {
        String path = "/static/wav/" +file+".mp3";
        Process exec = Runtime.getRuntime().exec("play " + path);
        exec.waitFor();
        return "ok";
    }
}
