//Edge 语音合成

import chrome.edge; 
var theApp = chrome.edge.app();

import sys.audioVolume;
var volumeCtrl = sys.audioVolume();

theApp.external = {
    getVolume = function(){
    	return volumeCtrl.volume;
    }
    setVolume = function(v){ 
    	volumeCtrl.volume = tonumber(v);
    }   
}

theApp.httpHandler["/res/index.aardio" ] = function(response,request){
	response.write(`
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">
    <title>edge 语音合成</title>
    <script src="/aardio.js"></script>
</head>

<body style="margin:15px;line-height:180%">
    <form>
        <div>
            <label>请选择语音：<select> </select></lable><br>
                <label for="volume">系统音量:<input type="range" min="0" max="100" step="1" id="volume"><span
                        class="volume-value">1</span></label>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <label for="rate">速度:<input type="range" min="0.5" max="2" value="1" step="0.1" id="rate"><span
                        class="rate-value">1</span></label>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <label for="pitch">音调:<input type="range" min="0" max="2" value="1" step="0.1" id="pitch"> <span
                        class="pitch-value">1</span></label>
        </div>

        <div class="controls">
            <button id="play" type="submit" style="margin-top:5px">大声朗读下面输入的文本</button>
        </div>

        <textarea rows="30" cols="133" id="txt" name="txt" autofocus style="margin-top:10px"></textarea>

    </form>

    <script>
        var synth = window.speechSynthesis;

        var inputForm = document.querySelector('form');
        var inputTxt = document.querySelector('#txt');
        var voiceSelect = document.querySelector('select');

        var volume = document.querySelector('#volume');
        var volumeValue = document.querySelector('.volume-value');
        var pitch = document.querySelector('#pitch');
        var pitchValue = document.querySelector('.pitch-value');
        var rate = document.querySelector('#rate');
        var rateValue = document.querySelector('.rate-value');

        var voices = [];

        function populateVoiceList() {
            voices = synth.getVoices().sort(function (a, b) {
                const aname = a.name.toUpperCase(), bname = b.name.toUpperCase();
                if (aname < bname) return -1;
                else if (aname == bname) return 0;
                else return +1;
            });
            var selectedIndex = voiceSelect.selectedIndex < 0 ? 0 : voiceSelect.selectedIndex;
            voiceSelect.innerHTML = '';
            for (i = 0; i < voices.length; i++) {
                var option = document.createElement('option');
                option.textContent = voices[i].name + ' (' + voices[i].lang + ')';

                if (voices[i].default) {
                    option.textContent += ' -- DEFAULT';
                }

                option.setAttribute('data-lang', voices[i].lang);
                option.setAttribute('data-name', voices[i].name);
                if (voices[i].name.indexOf("Xiaoxiao") > 0) {
                    selectedIndex = i;
                }
                voiceSelect.appendChild(option);
            }
            voiceSelect.selectedIndex = selectedIndex;
        }

        populateVoiceList();
        if (speechSynthesis.onvoiceschanged !== undefined) {
            speechSynthesis.onvoiceschanged = populateVoiceList;
        }

        function speak() {
            if (synth.speaking) {
                console.error('speechSynthesis.speaking');
                return;
            }
            
            var txt = inputTxt.value;
            if( txt === '' ) txt = "请先输入要朗读的文本";
            var utterThis = new SpeechSynthesisUtterance(txt);
            utterThis.onend = function (event) {
                console.log('SpeechSynthesisUtterance.onend');
            }
            utterThis.onerror = function (event) {
                console.error('SpeechSynthesisUtterance.onerror');
            }
            var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
            for (i = 0; i < voices.length; i++) {
                if (voices[i].name === selectedOption) {
                    utterThis.voice = voices[i];
                    break;
                }
            }
            utterThis.pitch = pitch.value;
            utterThis.rate = rate.value;
            synth.speak(utterThis);
        }

        inputForm.onsubmit = function (event) {
            event.preventDefault();

            speak();

            inputTxt.blur();
        }

        pitch.onchange = function () {
            pitchValue.textContent = pitch.value;
        }

        rate.onchange = function () {
            rateValue.textContent = rate.value;
        }

        volume.onchange = function () {
            volumeValue.textContent = volume.value;
            aardio.setVolume(volume.value);
        }

        aardio.getVolume().then(v => { volume.value = v; volume.onchange() })

        voiceSelect.onchange = function () {
            speak();
        }
    </script>
</body>
</html>
	`)
}


//调整窗口大小
theApp.indexReady(
	function(){
		theApp.setPos(20,20,1080,720)
	} 
)

//正式的启动chrome进程
theApp.start("/res/index.aardio")

//网页中可以调用 aardio.quit() 退出,也可以直接关闭chrome窗口退出
win.loopMessage();
