<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>SayTeX</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML' async></script>
    <link rel="stylesheet" href="{{ url_for('static', filename=css_filename) }}">
    <meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0">
</head>
<body>

<script>
    function copyToClipboard(copy_from_class) {
        // Select the copy anchor text
        window.getSelection().removeAllRanges();
        var emailLink = document.querySelector(copy_from_class);
        var range = document.createRange();
        range.selectNode(emailLink);
        window.getSelection().addRange(range);

        try {
            // Now that we've selected the anchor text, execute the copy command
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy email command was ' + msg);
        } catch(err) {
            console.log('Oops, unable to copy');
        }

        // Remove the selections - NOTE: Should use
        // removeRange(range) when it is supported
        window.getSelection().removeAllRanges();
    }
</script>

<div id='allcontent'>

    <h1>SayTeX Demo</h1>

    <div id="editorcontrolpanel">
        <button id="startButton" disabled>Start</button>
        <div id="editorcontextualstatusdiv">

            <a style="display:none;" id="stopButton">Stop</a>
            <span style="display:none;" id="editorcontextualstatusmessage">Finished.</span>
            <span id="editorcontextualstatusplaceholder">Meh.</span>
        
        </div>
    </div>


    <div id="fastapi" class='latexsection'>

        <p class="displaylatex">
        $$\sum_{n = 1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}$$
        </p>

        <code class="rawlatex" contenteditable='true' spellcheck="false">
            \sum_{n = 1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}
            </code>

            <div>
                <button class="copybutton" onclick="copyToClipboard('#fastapi .rawlatex')">Copy LaTeX</button>
            </div>
        
        <hr style="margin-top: 1.5em">

        <h6>Speech Recognition Input</h6>

        <code class="naturalinput" contenteditable="true" spellcheck="false">
            sum from n equals one to infinity of one over n squared equals pi squared over six
        </code>

        <h6>SayTeX Syntax</h6>

        <code class="saytexsyntax" contenteditable="true" spellcheck="false">
            sum subscript begin n equals 1 end superscript begin infinity end fraction begin 1 end begin n superscript 2 end equals fraction begin pi superscript 2 end begin 6 end
        </code>


        

        

    </div>





    <p id="curtext" style="display:none;">
    </p>
    <br>




</div>


<!-- SDK reference goes here -->
<script src="{{ url_for('static', filename='microsoft.cognitiveservices.speech.sdk.bundle.js') }}"></script>

<script>
    // status fields and start button in UI
    var fastRawLatexField;
    var fastDisplayLatexField;
    var fullRawLatexField;
    var fullDisplayLatexField;
    var startButton;
    var curtext = "";
    var ncurtext = "";

    // region key and authorization token for speech services
    var regionKey = '{{ microsoft_region_key }}';
    var authorizationToken = '{{ microsoft_authorization_token }}';
    var SpeechSDK;
    var recognizer;


    // An enum containing the URL paths for the Latex API
    var LatexAPIURL = '{{ api_url }}' + '/latex/';
    var SaytexAPIURL = '{{ api_url }}' + '/saytex/'
    function callLatexAPI(apiurl, text, rawfield, displayfield) {
        /*
        Calls the LaTeX API.

        params:
            - apiurl:       str, a value of the enum LatexAPIURLs
            - text:         str, to be sent to API (unencoded)
            - rawfield:     html object, containing raw latex
            - displayfield: html object, containing display latex

        returns:
            [nothing]
        */

        fetch(apiurl + encodeURIComponent(text))
            .then(function(response) {
                return response.text();
            })
            .then(function(mytext) {
                console.log(mytext)

                if(mytext==' '){
                    return;
                }
                rawfield.innerHTML =  mytext;

                if (displayfield !== null) {
                    displayfield.innerHTML = "$$" + mytext + "$$";
                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                }
        });
    }

    function rawLatexChange(rawfield, displayfield) {
        displayfield.innerHTML = '$$' + rawfield.innerHTML.trim() + '$$';
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    }
    function saytexSyntaxChange(syntaxfield, rawfield, displayfield) {
        callLatexAPI(LatexAPIURL, syntaxfield.innerHTML.trim(), rawfield, displayfield);
    }
    function naturalLangChange(naturalfield, syntaxfield, rawfield, displayfield) {
        var nattext = naturalfield.innerHTML.trim()
        nattext = nattext.replace('&nbsp;', ' ');
        callLatexAPI(LatexAPIURL, nattext, rawfield, displayfield);
        callLatexAPI(SaytexAPIURL, nattext, syntaxfield, null);
    }


    document.addEventListener("DOMContentLoaded", function () {
        startButton = document.getElementById("startButton");
        stopButton = document.getElementById("stopButton");
        fastRawLatexField = document.querySelector("#fastapi .rawlatex");
        fastDisplayLatexField = document.querySelector("#fastapi .displaylatex");
        naturalInputField = document.querySelector("#fastapi .naturalinput");
        saytexSyntaxField = document.querySelector("#fastapi .saytexsyntax")


        fastRawLatexField.addEventListener('input', function() {
            rawLatexChange(fastRawLatexField,fastDisplayLatexField);
        });
        saytexSyntaxField.addEventListener('input', function() {
            saytexSyntaxChange(saytexSyntaxField, fastRawLatexField, fastDisplayLatexField);
        });
        naturalInputField.addEventListener('input', function() {
            naturalLangChange(naturalInputField, saytexSyntaxField, fastRawLatexField, fastDisplayLatexField);
        });


        startButton.addEventListener("click", function () {

            curtext = '';


            // if we got an authorization token, use the token. otherwise error
            var speechConfig;
            if (authorizationToken) {
                speechConfig = SpeechSDK.SpeechConfig.fromAuthorizationToken(authorizationToken, regionKey);
            } else {
                console.error('No authorization token obtained. Something wrong.');
            }

            speechConfig.speechRecognitionLanguage = "en-US";
            var audioConfig  = SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
            recognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);

            
            recognizer.recognizing = function (r, ev) {
                console.log('recognizing!');

                text = ev.result.text;
                console.log(text);

                text = curtext + text;
                ncurtext = text;

                // call the fast API!
                naturalInputField.innerHTML = text
                callLatexAPI(LatexAPIURL, text, fastRawLatexField, fastDisplayLatexField);
                callLatexAPI(SaytexAPIURL, text, saytexSyntaxField, null);
            };
            recognizer.recognized = function (r, ev) {
                console.log('recognized!');
                //curtext += ev.result.text;
                // don't use recognized event because it tries to make sentences with grammar which is often really bad
                curtext = ncurtext;
                /*if (curtext.endsWith('.')) {
                    curtext = curtext.slice(0, -1);
                }*/
                curtext += ' ';
                console.log(curtext);

                // call the full API!
                //callLatexAPI(LatexAPIURLs.FULL, curtext, fullRawLatexField, fullDisplayLatexField);
            };


            recognizer.startContinuousRecognitionAsync(
            function (result) {
                //startRecognizeOnceAsyncButton.disabled = false;
                //phraseDiv.innerHTML += result.text;
                //window.console.log(result);

                //recognizer.close();
                //recognizer = undefined;
                startButton.innerHTML = "Listening...";
                startButton.className = "editorrunbuttonrunning";
                startButton.disabled = true;
                stopButton.disabled = false;
                stopButton.style.display = "inline";
                document.getElementById("editorcontextualstatusplaceholder").style.display = "none";
                console.log('starting continuous speech recognition');
            },
            function (err) {
                startButton.disabled = false;
                startButton.innerHTML = "Start";
                startButton.className = "";
                stopButton.disabled = true;
                stopButton.style.display = "none";
                document.getElementById("editorcontextualstatusplaceholder").style.display = "inline";
                window.console.log(err);

                recognizer.close();
                recognizer = undefined;
            });
        });
        stopButton.addEventListener("click", function () {
            startButton.disabled = false;
            startButton.innerHTML = "Start";
            startButton.className = "";
            stopButton.disabled = true;
            stopButton.style.display = "none";
            document.getElementById("editorcontextualstatusplaceholder").style.display = "inline";

            recognizer.stopContinuousRecognitionAsync(
                function(result) {
                    console.log('stopping continuous speech recognition');

                    // call the full API!
                    // use the ncurtext since that contains the most recent version
                    //callLatexAPI(LatexAPIURLs.FULL, ncurtext, fullRawLatexField, fullDisplayLatexField);
                    
                },
                function (err) {
                    console.log(err);
                }
            );
        });

        if (!!window.SpeechSDK) {
            SpeechSDK = window.SpeechSDK;
            startButton.disabled = false;

        }
    });


</script>


 <!-- Optional authorization token request goes here -->

 <!-- Sample code goes here -->
</body>
</html>
