//<script>

(function() {
    "use strict"

    function InputVoiceEnter(selector, options, callback) {

        this.options = options || {}
        this.options.submitClosestForm = this.options.submitClosestForm || false
        this.options.button = this.options.button || false
        this.options.buttonPosition = this.options.buttonPosition || {}

        this.input = document.querySelector(selector)
        this.selector = selector

        this.callback = callback;

        if (!this.input) {
            return
        }

        if (!FLGlobalConfig.languages[FLGlobalConfig.lang].bcp) {
            return;
        }

        if (options.button) {
            this.voice_btn = document.querySelector(options.button)
            if (!this.voice_btn) {
                throw new Error("Button not found: " + selector);
            }
        } else {
            this.createMicBtn()
        }

        const speechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
        this.recognition = new speechRecognition()
        this.recognition.lang = FLGlobalConfig.languages[FLGlobalConfig.lang].bcp
        this.recognition.continuous = false

        this.assignHandlers()
    }

    InputVoiceEnter.prototype.createMicBtn = function () {

        const parent = this.input.parentElement

        const wrapper = document.createElement('div')
        parent.appendChild(wrapper)

        wrapper.appendChild(this.input)
        wrapper.style.position = 'relative'

        const aWrapper = document.createElement('div')
        wrapper.appendChild(aWrapper)
        aWrapper.style.position = this.options.buttonPosition.position || 'absolute'
        aWrapper.style.right = this.options.buttonPosition.right || '5px'
        aWrapper.style.top = this.options.buttonPosition.top || '50%'
        aWrapper.style.transform = this.options.buttonPosition.transform || 'translateY(-50%)'


        const a = document.createElement('a')
        aWrapper.appendChild(a)
        a.href = '#'

        const i = document.createElement('i')
        a.appendChild(i);
        i.className = "fa fa-microphone"
        i.setAttribute('aria-hidden', 'true')

        this.voice_btn = a
    }

    InputVoiceEnter.prototype.capitalizeFirstLetter = function (string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    InputVoiceEnter.prototype.assignHandlers = function () {

        this.voice_btn.addEventListener('click',  () => {
            this.input.value = voiceLanguagesVars.pleaseSpeak
            this.recognition.start()
            this.isRecognized = false
            this.createAnimation()
            this.postMessage('onMicButtonClick')
        })

        this.recognition.onresult = (event) => {

            this.isRecognized = true
            this.removeAnimation()
            this.input.value = event.results[0][0].transcript
            this.submitClosestForm()
            this.callback(event.results[0][0].transcript)


            // $('#product_names').val(this.capitalizeFirstLetter(event.results[0][0].transcript));
            // $('#product_names').trigger('change');
        };

        this.recognition.onend = (event) => {
            this.removeAnimation()
            if (!this.isRecognized) {
                this.input.value = ''
            }
        }

        this.input.addEventListener('onVoiceRecognized',  (event) => {
            const input = document.querySelector(event.detail.selector)
            if (input) {
                input.value = event.detail.result
                this.submitClosestForm()
            }
        })
    }

    InputVoiceEnter.prototype.submitClosestForm = function () {
        if (this.options.submitClosestForm) {
            const form = this.input.closest('form')
            if (form) {
                form.submit()
            }
        }
    }

    InputVoiceEnter.prototype.createKeyframeStyle = function () {
        const soundAnimationStyle = document.createElement('style');
        soundAnimationStyle.textContent = `
@keyframes sound {
    0% {
        opacity: .35;
        height: 3px;
    }
    100% {
        opacity: 1;
        height: 20px;
    }
}
`;
        document.head.appendChild(soundAnimationStyle);
    }

    InputVoiceEnter.prototype.createAnimation = function () {

        this.createKeyframeStyle()

        const divElement = document.createElement('div');
        this.animation = divElement

        for (let i = 0; i < 3; i++) {
            const barElement = document.createElement('div');
            divElement.appendChild(barElement);

            barElement.style.background = '#52467b';
            barElement.style.bottom = '1px';
            barElement.style.height = '3px';
            barElement.style.width = '3px';
            barElement.style.margin = '0px 2px';
            barElement.style.borderRadius = '5px';
            barElement.style.animation = 'sound 0ms -600ms linear infinite alternate';

            switch (i) {
                case 0:
                    barElement.style.left = '1px';
                    barElement.style.animationDuration = '474ms';
                    break;
                case 1:
                    barElement.style.left = '15px';
                    barElement.style.animationDuration = '433ms';
                    break;
                case 2:
                    barElement.style.left = '29px';
                    barElement.style.animationDuration = '407ms';
                    break;
                default:
                    break;
            }
        }

        divElement.style.display = 'flex';
        divElement.style.justifyContent = 'center';
        divElement.style.alignItems = 'center';

        this.voice_btn.style.display = 'none'
        this.voice_btn.parentNode.insertBefore(divElement, this.voice_btn.nextSibling);
    }

    InputVoiceEnter.prototype.removeAnimation = function () {
        this.animation.remove()
        this.voice_btn.style.display = 'inline'
    }

    InputVoiceEnter.prototype.postMessage = function (event) {

        if (typeof window.webkit === 'undefined') {
            return
        }

        const message = {
            event: event,
            lang: FLGlobalConfig.lang,
            selector: this.selector
        }

        window.webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));
    }

    window.InputVoiceEnter = InputVoiceEnter;

})();