/**
 * Copyright (C) 2020 to the present, Crestron Electronics, Inc.
 * All rights reserved.
 * No part of this software may be reproduced in any form, machine
 * or natural, without the express written consent of Crestron Electronics.
 * Use of this source code is subject to the terms of the Crestron Software License Agreement 
 * under which you licensed this source code.  
 *
 * This code was automatically generated by Crestron's code generation tool.
 */

/* jslint es6 */

const footerModule = (function () {
    'use strict';

    const micMuteBtn = document.getElementById('micMuteBtn');
    const volumeMuteBtn = document.getElementById('volumeMuteBtn');
    const infoBtn = document.getElementById('infoBtn');
    const volumeProgressBar = document.getElementById('volumeProgressBar');
    const menuIconFooterPage = document.getElementById("menuIconFooterPage");
    const backButtonFooterPage = document.getElementById("backButtonFooterPage");

    let arrayOfSubscriptions = [];
    let autoHideTimer = null;
    let infoBtnTimer = 0;
    let volumeControl = "ch5-button.volume-btn";
    let canShowBasicInfo = true;

    let avfMuteStates = {};
    avfMuteStates.isSpeakerMuted = false;
    avfMuteStates.isMicMuted = false;
    let subHardButton4 = null;
    let subHardButton5 = null;
    let subHardButton6 = null;
    let subFooterIsMicMuted = null;
    let subFooterIsSpeakerMuted = null;
    let subFooterVolume = null;

    /**
     * Initialize Method
     */
    function onInit() {
        invokeUnsubscriptions();
        initializeVariables();
        invokeSubscriptions();
        bindEventListeners();
    }

    /**
     * 
     */
    function invokeSubscriptions() {
        subHardButton4 = CrComLib.subscribeState('b', 'Csig.Hard_Button_4.Press', (response) => {
            avfUtility.log('Csig.Hard_Button_4.Press: ', response);
            CrComLib.publishEvent('b', 'Room[0].Audio.RaiseVolume.Execute', response);
            if (avfUtility.toBool(response)) {
                showHideVolumeProgressBar(true);
            }
        });

        subHardButton5 = CrComLib.subscribeState('b', 'Csig.Hard_Button_5.Press', (response) => {
            avfUtility.log('Csig.Hard_Button_5.Press: ', response);
            CrComLib.publishEvent('b', 'Room[0].Audio.LowerVolume.Execute', response);
            if (avfUtility.toBool(response)) {
                showHideVolumeProgressBar(true);
            }
        });

        subHardButton6 = CrComLib.subscribeState('b', 'Csig.Hard_Button_6.Press', (response) => {
            avfUtility.log('Csig.Hard_Button_6.Press: ', response);
            CrComLib.publishEvent('b', 'Room[0].Audio.MuteMic.Execute', response);
        });

        subFooterIsMicMuted = CrComLib.subscribeState('b', 'Room[0].Audio.IsMicMuted', (response) => {
            avfUtility.log('Room[0].Audio.IsMicMuted: ', response);
            avfMuteStates.isMicMuted = avfUtility.toBool(response);
            updateMuteImages();
        });

        subFooterIsSpeakerMuted = CrComLib.subscribeState('b', 'Room[0].Audio.IsSpeakerMuted', (response) => {
            avfUtility.log('Room[0].Audio.IsSpeakerMuted: ', response);
            avfMuteStates.isSpeakerMuted = avfUtility.toBool(response);
            updateMuteImages();
        });

        subFooterVolume = CrComLib.subscribeState('n', 'Room[0].Audio.Volume', (response) => {
            avfUtility.log('Room[0].Audio.Volume: ', response);
            if (isSubscribed('Room[0].Audio.Volume')) {
                showHideVolumeProgressBar(true);
            }
            subscribeToArray('Room[0].Audio.Volume');
        });
    }

    /**
     * Check if the input is subscribed. These are helpful for situations where we want to subscribe 
     * but want to use the subscription value only from the second time onwards.
     * @param {string} input 
     */
    function isSubscribed(input) {
        return arrayOfSubscriptions.includes(input);
    }

    /**
     * Add to Array of subscribed key
     * @param {string} input 
     */
    function subscribeToArray(input) {
        arrayOfSubscriptions.push(input);
    }

    /**
     * Change the value icon on the basis of subscribe data
     */
    function updateMuteImages() {
        if (avfMuteStates.isMicMuted) {
            micMuteBtn.setAttribute("iconurl", "./app/project/assets/img/avf/mic_mute_red.png");
            setRedRing(micMuteBtn, true);
            setRedBorder(true);
        } else {
            micMuteBtn.setAttribute("iconurl", "./app/project/assets/img/avf/mic_mute_gray.png");
            setRedRing(micMuteBtn, false);
            setRedBorder(false);
        }
        if (avfMuteStates.isSpeakerMuted) {
            volumeMuteBtn.setAttribute("iconurl", "./app/project/assets/img/avf/vol_mute_red.png");
            setRedRing(volumeMuteBtn, true);
        } else {
            volumeMuteBtn.setAttribute("iconurl", "./app/project/assets/img/avf/vol_mute_blk_gray.png");
            setRedRing(volumeMuteBtn, false);
        }
    }

    /**
     * Add the red circle around toolbar button if inactive
     * @param {node} target
     * @param {boolean} enable
     */
    function setRedRing(target, enable) {
        let imageIconsEle = "button.cb-btn";
        target.classList.remove("red-mute-mic");
        target.querySelector(imageIconsEle).classList.remove("toobar-active-icon");

        if (enable) {
            target.classList.add("red-mute-mic");
            target.querySelector(imageIconsEle).classList.add("toobar-active-icon");
        }
    }

    /**
     * Add the red boader to body of the page
     * @param {boolean} enable 
     */
    function setRedBorder(enableBorder) {
        let screenBody = document.querySelector('body');
        screenBody.classList.remove("selected-element");
        if (enableBorder) {
            screenBody.classList.add("selected-element");
        }
    }

    /**
     * Shows the volume progressbar only when volume-up and volum-down button pressed otherwise its hide the progress bar
     * @param {event} event attached to target element
     */
    function showHideVolumeProgressBar(event) {
        let isVolumeIconsClicked = false;
        if (typeof event === "boolean") {
            isVolumeIconsClicked = event;
        } else {
            isVolumeIconsClicked = event.target.closest(volumeControl) !== null;
        }
        if (autoHideTimer != null) {
            clearTimeout(autoHideTimer);
            autoHideTimer = null;
        }
        volumeProgressBar.style.display = (isVolumeIconsClicked) ? "block" : "none";
        if (isVolumeIconsClicked) {
            removeVolumeMuteSelection();
            autoHideVolumeProgressBar();
        }
    }

    /**
     * Remove mute state of volume
     */
    function removeVolumeMuteSelection() {
        const hasRedIcon = volumeMuteBtn.getElementsByTagName('img')[0].classList.contains('red-mute-mic');
        if (hasRedIcon) {
            CrComLib.publishEvent('s', 'receive_volume_mute_url', "./app/project/assets/img/avf/vol_mute_blk_gray.png");
            volumeMuteBtn.getElementsByTagName('img')[0].classList.remove("red-mute-mic");
            volumeMuteBtn.classList.remove("toobar-active-icon");
        }
    }

    /**
     * Auto hide volume progress bar after 5 sec if no events trigger
     */
    function autoHideVolumeProgressBar() {
        autoHideTimer = setTimeout(() => {
            if (!volumeProgressBar) {
                volumeProgressBar = document.getElementById('volumeProgressBar');
            }
            volumeProgressBar.style.display = "none";
        }, 5000);
    }

    /**
     * Show the info page / help page
     */
    function showBasicInfo() {
        clearTimeout(infoBtnTimer);
        if (canShowBasicInfo) {
            setTimeout(() => {
                if (helpModule.showCustomHelpPage()) {
                    navigationModule.openPopup(navigationModule.popupPages.helpImportPage);
                } else {
                    navigationModule.openPopup(navigationModule.popupPages.infoImportPage);
                }
            }, 30);
        }
        canShowBasicInfo = true;
    }

    /**
     * Show Back button icon
     */
    function showBackIcon() {
        backButtonFooterPage.style.display = "block";
        menuIconFooterPage.style.display = "none";
    }

    /**
     * Show Menu Icon
     */
    function showMenuIcon() {
        backButtonFooterPage.style.display = "none";
        menuIconFooterPage.style.display = "block";
    }

    /**
     * Show the detailed info screen
     */
    function showExtendedInfo() {
        infoBtnTimer = window.setTimeout(() => {
            canShowBasicInfo = false;
            navigationModule.openPopup(navigationModule.popupPages.extendedInfoImportPage);
        }, 2000);
    }

    /**
     * Execute mute speaker
     */
    function executeMuteSpeaker() {
        CrComLib.publishEvent('b', 'Room[0].Audio.MuteSpeaker.Execute', false);
        CrComLib.publishEvent('b', 'Room[0].Audio.MuteSpeaker.Execute', true);
    }

    /**
     * Execute mute mic
     */
    function executeMuteMic() {
        CrComLib.publishEvent('b', 'Room[0].Audio.MuteMic.Execute', false);
        CrComLib.publishEvent('b', 'Room[0].Audio.MuteMic.Execute', true);
    }

    /**
     * 
     */
    function goToMenuScreen() {
        navigationModule.goToPage(navigationModule.navigationPages.menuScreenImportPage);
    }

    /**
     * 
     */
    function backButtonMenuIconClicked() {
        navigationModule.backButtonMenuIconClicked();
    }

    /**
     * Invoke unsubscriptions related to module
     */
    function invokeUnsubscriptions() {
        if (subHardButton4) {
            CrComLib.unsubscribeState('b', 'Csig.Hard_Button_4.Press', subHardButton4);
        }
        if (subHardButton5) {
            CrComLib.unsubscribeState('b', 'Csig.Hard_Button_5.Press', subHardButton5);
        }
        if (subHardButton6) {
            CrComLib.unsubscribeState('b', 'Csig.Hard_Button_6.Press', subHardButton6);
        }
        if (subFooterIsMicMuted) {
            CrComLib.unsubscribeState('b', 'Room[0].Audio.IsMicMuted', subFooterIsMicMuted);
        }
        if (subFooterIsSpeakerMuted) {
            CrComLib.unsubscribeState('b', 'Room[0].Audio.IsSpeakerMuted', subFooterIsSpeakerMuted);
        }
        if (subFooterVolume) {
            CrComLib.unsubscribeState('n', 'Room[0].Audio.Volume', subFooterVolume);
        }
    }

    /**
     * Initialize all the variables used in this module
     */
    function initializeVariables() {
        subHardButton4 = null;
        subHardButton5 = null;
        subHardButton6 = null;
        subFooterIsMicMuted = null;
        subFooterIsSpeakerMuted = null;
        subFooterVolume = null;
    }

    /**
     * execute LowerVolume - lowering volume on touch start
     */
    function executeLowerVolume() {
        CrComLib.publishEvent('b', 'Room[0].Audio.LowerVolume.Execute', false);
        CrComLib.publishEvent('b', 'Room[0].Audio.LowerVolume.Execute', true);
    }

    /**
     * execute RaiseVolume - raising volume on touch start
     */
    function executeRaiseVolume() {
        CrComLib.publishEvent('b', 'Room[0].Audio.RaiseVolume.Execute', false);
        CrComLib.publishEvent('b', 'Room[0].Audio.RaiseVolume.Execute', true);
    }

    /**
     * Function to bind event listeners to elements
     */
    function bindEventListeners() {
        document.addEventListener('click', showHideVolumeProgressBar, false);
        infoBtn.addEventListener('touchstart', showExtendedInfo, false);
        infoBtn.addEventListener('touchend', showBasicInfo, false);
        menuIconFooterPage.addEventListener("click", goToMenuScreen, false);
        backButtonFooterPage.addEventListener("click", backButtonMenuIconClicked, false);
    }

    /**
     * All public method and properties are exported here
     */
    return {
        onInit,
        showMenuIcon,
        showBackIcon
    };

}());