!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
    <meta name="description" content="Improve">
</head>
<style>
    html {
        background-color: #176498;
        box-sizing: border-box;
        margin: 0;
        padding: 0;
    }

    *,
    *:before,
    *:after {
        box-sizing: inherit;
    }

    body {
        font: 14px/1.5 Tahoma, sans-serif;
    }

    p {
        margin-top: 50px;
    }

    .input-field__wrapper {
        background-color: #ddd;
        border-radius: 4px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
        margin: 50px auto 0;
        padding: 30px 30px 30px;
        position: relative;
        width: 500px;
    }

    .input-field {
        font: inherit;
        padding: 5px 10px;
        width: 350px;
    }

    .input-field__microphone {
        cursor: pointer;
        font-size: 24px;
        position: absolute;
        right: 125px;
        bottom: 30px;
        transition: filter 500ms;
    }

    .input-field__microphone--hidden {
        display: none;
    }

    .input-field__microphone--active {
        filter: drop-shadow(0 0 10px #d44);
    }

    .input-field__button {
        background-color: #ff0000;
        border: 0;
        border-radius: 2px;
        color: #fff;
        cursor: pointer;
        font: inherit;
        float: right;
        margin-top: 5px;
        min-width: 78px;
        padding: 6px 20px;
    }

    .input-field:invalid~.input-field__button {
        background-color: #e26d00;
        color: #fff;
        cursor: default;
    }
</style>

<body>
    <div class="input-field__wrapper">
        <input id="js-voice-output" class="input-field" required>
        <button class="input-field__button">Search</button>
        <span class="input-field__microphone input-field__microphone--hidden">🎙️</span>
    </div>

    <script>
        window.philips = window.philips || {};

        philips.speechToText = (() => {
            const SpeechRecognition = window.SpeechRecognition || webkitSpeechRecognition;
            const SpeechGrammarList = window.SpeechGrammarList || webkitSpeechGrammarList;

            // DOM elements
            const $searchText = document.querySelector('.input-field');
            const $microphone = document.querySelector('.input-field__microphone');
            const $button = document.querySelector('.input-field__button');

            /**
             * @description  Set up all the proper variables / setting for SpeechRecognition.
             * @returns  {object} - SpeechRecognitions 'recognition' object.
             * @example  startListening();
             */
            const setUpSpeechRecognition = () => {
                // Products
                const products = [
                    'airfryer',
                    'avent',
                    'blender',
                    'erzatsteile',
                    'hue',
                    'lumea',
                    'oneblade',
                    'ontkalker',
                    'padhouder',
                    'senseo',
                    'sonicare',
                    'speedpro',
                    'steamer',
                    'toothbrush',
                    'tv',
                    'waterreservoir'
                ];

                // Speech Recognition
                const grammar = `#JSGF V1.0; grammar names; public <name> = ${products.join(' | ')} ;`;
                const recognition = new SpeechRecognition();
                const speechRecognitionList = new SpeechGrammarList();

                speechRecognitionList.addFromString(grammar, 1);
                recognition.grammars = speechRecognitionList;
                recognition.lang = 'en-GB';
                recognition.interimResults = true;
                recognition.maxAlternatives = 1;

                return recognition;
            };

            /**
             * @description  Start listening for user input.
             * @returns  {void} - This function doesn't return anything.
             * @example  startListening();
             */
            const startListening = () => {
                recognition = setUpSpeechRecognition();

                recognition.start();

                recognition.onresult = (event) => {
                    const last = event.results.length - 1;
                    const product = event.results[last][0].transcript;

                    document.querySelector('#js-voice-output').setAttribute('value', product);

                    // console.log(`Result received: ${product}.`);
                    // console.log(`Confidence: ${event.results[0][0].confidence}`);
                    // console.log(event);
                };

                recognition.onend = () => {
                    $microphone.classList.remove('input-field__microphone--active');
                };

                recognition.onspeechend = () => {
                    recognition.stop();
                };

                recognition.onnomatch = () => {
                    console.log('I didn\'t recognise that.');
                };

                recognition.onerror = (event) => {
                    console.log(`Error occurred in recognition: ${event.error}`);
                };
            };


            /**
             * @description  Initialize the Speech to Text function.
             * @returns  {void} - This function doesn't return anything.
             * @example  initialize();
             */
            const initialize = () => {
                $microphone.classList.remove('input-field__microphone--hidden');
                $microphone.addEventListener('click', () => {
                    $microphone.classList.add('input-field__microphone--active');
                    // console.log('Ready to receive your command.');
                    startListening();
                });

                $button.addEventListener('click', () => {
                    if ($searchText.value !== '') {
                        var url = 'https://www.google.com/search?q=' + $searchText.value;
                        window.open(url, '_blank');
                    }
                });
            };

            if (SpeechRecognition && SpeechGrammarList) {
                document.addEventListener('DOMContentLoaded', () => {
                    initialize();
                });
            }
        })();
    </script>
</body>

</html>
