package main

import (
	"crypto/md5"
	"encoding/hex"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"sync"
	"time"

	"github.com/chenqinghe/baidu-ai-go-sdk/voice"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

var client *voice.VoiceClient
var addr string

const (
	apiKey    = "tVPKdPqxKwWOM9vsukPzseoH"
	apiSecret = "VFusINaQ3YjDUC4GoIB1cENME9g2f4Gn"
)

func init() {
	client = voice.NewVoiceClient(apiKey, apiSecret)

	flag.StringVar(&addr, "addr", ":8080", "server address")

}

func main() {
	flag.Parse()
	if addr == "" {
		flag.Usage()
		os.Exit(1)
	}

	r := gin.Default()

	handler := &handler{
		l: &sync.Mutex{},
	}
	r.GET("/", handler.tts)
	if err := r.Run(":8080"); err != nil {
		logrus.Fatalln("start server error:", err)
	}
}

type handler struct {
	l *sync.Mutex // 确保串行，不然会同时播放多个语音
}

func (h *handler) tts(c *gin.Context) {
	h.l.Lock()
	defer h.l.Unlock()
	content := c.Query("q")
	logrus.Infoln("tts content:", content)

	data, err := client.TextToSpeech(content)
	if err != nil {
		logrus.Errorln("sdk::TextToSpeech error:", err, "content:", content)
		http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
		return
	}

	filename := fmt.Sprintf("/tmp/%s.mp3", randomStr())
	err = ioutil.WriteFile(filename, data, os.ModePerm)
	if err != nil {
		logrus.Errorln("write file error:", err, "path:", filename)
		http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
		return
	}
	defer os.Remove(filename)

	cmd := exec.Command("mplayer", filename)
	if err := cmd.Run(); err != nil {
		logrus.Errorln("play error:", err)
		http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
		return
	}
	c.Writer.WriteHeader(http.StatusOK)
	c.Writer.WriteString("ok")

}

func randomStr() string {
	now := time.Now().Format("2006-01-02 15:04:05 9999")
	h := md5.New()

	h.Write([]byte(now))
	r := h.Sum(nil)
	return hex.EncodeToString(r)
}
