package stt

import (
	"encoding/json"
	"strings"
	"time"

	"gitlab.com/cinnamon/voiceagent/icserror"
	"gitlab.com/cinnamon/voiceagent/icslog"
	"gitlab.com/cinnamon/voiceagent/icsws"
)

type LGSTTParam struct {
	UserName       string `json:"USERNAME"`
	UpdateInternal int    `json:"UPDATEINTERVAL"`
	EPDProcess     string `json:"EPD_PROCESS"`
	ClinetType     string `json:"CLIENT_TYPE"`
}

func sttLG(voicedata []byte) (string, *icserror.IcsError) {
	var trstring string
	l := icslog.GetIcsLog()

	voicedataLen := len(voicedata)
	startPos := 0
	endPos := 8000

	ws := icsws.NewWSClient("18.183.222.16:9998", "")
	werr := ws.Connect()
	if werr != nil {
		l.Printf(icslog.LOG_LEVEL_ERROR, -1, "Failed to connect to LG STT Websocket server[18.183.222.16:9998] - %s", werr.GetError())
		icserror.ICSERRSTTFail.SetError(werr.GetError())
		return "", icserror.ICSERRSTTFail
	}
	sttParam := LGSTTParam{
		UserName:       "LGECS",
		UpdateInternal: -1,
		EPDProcess:     "FALSE",
		ClinetType:     "APPLICATION",
	}
	param, jerr := json.Marshal(sttParam)
	if jerr != nil {
		l.Printf(icslog.LOG_LEVEL_ERROR, -1, "Failed to json marshal - %s", jerr)
		icserror.ICSERRSTTFail.SetError(jerr)
		return "", icserror.ICSERRSTTFail
	}
	werr = ws.WriteData(param)
	if werr != nil {
		l.Printf(icslog.LOG_LEVEL_ERROR, -1, "Failed to send to LG STT Websocket server[18.183.222.16:9998] - %s", werr.GetError())
		icserror.ICSERRSTTFail.SetError(werr.GetError())
		return "", icserror.ICSERRSTTFail
	}

	for {
		data, rerr := ws.Read()
		if rerr != nil {
			l.Printf(icslog.LOG_LEVEL_ERROR, -1, "Failed to read to LG STT Websocket server[18.183.222.16:9998] - %s", rerr.GetError())
			break
		}
		command := string(data)
		if strings.Compare(command, "DATA") == 0 {
			for {
				if endPos < voicedataLen {
					ws.WriteData(voicedata[startPos:endPos])
					startPos += 8000
					endPos += 8000
				} else {
					ws.WriteData(voicedata[startPos:voicedataLen])
					ws.Write("ENDOFSPEECH")
					break
				}
			}
		} else if strings.Contains(command, "RESULT:") {
			ws.Write("STOPLISTENING")
			//tr := strings.SplitN(command, "RESULT:", 2)[1]
			//trstring = tr[:len(tr)-1]
			trstring = strings.SplitN(command, "RESULT:", 2)[1]
		} else if strings.Contains(command, "MESSAGE:") {
			//tr := strings.SplitN(command, "MESSAGE:", 2)[1]
			//trstring = tr[:len(tr)-1]
			trstring = strings.SplitN(command, "MESSAGE:", 2)[1]
		} else if strings.Compare(command, "STOPLISTENING") == 0 {
			time.Sleep(time.Millisecond * 100)
			break
		}
	}

	return trstring, icserror.ICSERRSTTOK
}
