/**
 * 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 helpModule = (function () {
    'use strict';

    let isCustomHelpActive = false;
    let customHelpObj = document.getElementById("customHelp");
    let customImgUrl = "";
    let subHelpEnableCustomHelpPage = null;
    let subHelpCustomHelpPageUrl = null;
    let subHelpIPAddress = null;
    let ipAddress = "";
    let uriProtocol = "";
    let localIp = "";
    let portNumber = "";

    /**
     * Set custom help to inactive
     */
    function onInit() {
        invokeUnsubscriptions();
        initializeVariables();
        invokeSubscriptions();
    }

    /**
     * Invoke subscriptions related to module
     */
    function invokeSubscriptions() {
        subHelpEnableCustomHelpPage = CrComLib.subscribeState('b', 'Room[0].TouchScreenSettings.EnableCustomHelpPage', (response) => {
            avfUtility.log(`Room[0].TouchScreenSettings.EnableCustomHelpPage: ${response}`)
            setCustomHelpEnabled(avfUtility.toBool(response));
        });

        subHelpCustomHelpPageUrl = CrComLib.subscribeState('s', 'Room[0].TouchScreenSettings.CustomHelpPageUrl', (response) => {
            avfUtility.log(`Room[0].TouchScreenSettings.CustomHelpPageUrl: ${response}`)
            customImgUrl = response;
            setBackgroundImage();
        });

        subHelpIPAddress = CrComLib.subscribeState('s', 'Room[0].SystemInfo.IPAddress', (response) => {
            avfUtility.log(`Room[0].SystemInfo.IPAddress: ${response}`)
            setIPAddress(response);
        });
    }

    /**
     * Set the subscribe of whether custom help enabled or not
     * @param {boolean} val 
     */
    function setCustomHelpEnabled(val) {
        avfUtility.log(`setCustomHelpEnabled : ${val}`)
        isCustomHelpActive = val;
    }

    /**
     * Return server config status whether custom help is active or not
     */
    function showCustomHelpPage() {
        avfUtility.log(`showCustomHelpPage : ${isCustomHelpActive}`)
        return isCustomHelpActive;
    }

    /**
     * Validate the url to check whether imageUri has the correct url format
     * @param {string} imageUri Backgvround image url for customhelp page 
     */
    function isValidURL(imageUri) {
        return new Promise(function imgPromise(resolve, reject) {
            // Create the image
            const imgElement = new Image();
            // When image is loaded, resolve the promise
            imgElement.addEventListener('load', function imgOnLoad() {
                resolve(imageUri);
            });
            // When there's an error during load, reject the promise
            imgElement.addEventListener('error', function imgOnError() {
                reject();
            })
            imgElement.src = imageUri;
        });
    }

    /**
     * 
     */
    function setFallBackImageUrl() {
        const avfConfigInfo = configModule.getUrls();
        uriProtocol = avfConfigInfo.uriProtocol;
        localIp = avfConfigInfo.ipAddress;
        ipAddress = avfConfigInfo.ipAddress;
        portNumber = avfConfigInfo.portNumber;

        if (ipAddress === localIp) {
            ipAddress = "localhost";
        }
        let newIpAddress = uriProtocol + ipAddress + portNumber;
        return newIpAddress + "/img/blank.png";
    }

    /**
     * Set the background image for custom help page. If the image link is broken then set the "blank" image
     */
    function setBackgroundImage() {
        let bgUrl = "";
        isValidURL(customImgUrl).then(
            function fulfilled(img) {
                bgUrl = img.trim();
                customHelpObj.setAttribute("url", bgUrl);
            },
            function rejected() {
                bgUrl = setFallBackImageUrl();
                customHelpObj.setAttribute("url", bgUrl);
            }

        );
    }

    /**
     * Set IPAddress of dmps server
     * @param {string} v
     */
    function setIPAddress(v) {
        ipAddress = v;
        setBackgroundImage();
    }

    /**
     * Invoke unsubscriptions related to module
     */
    function invokeUnsubscriptions() {
        CrComLib.unsubscribeState('b', 'Room[0].TouchScreenSettings.EnableCustomHelpPage', subHelpEnableCustomHelpPage);
        CrComLib.unsubscribeState('s', 'Room[0].TouchScreenSettings.CustomHelpPageUrl', subHelpCustomHelpPageUrl);
        CrComLib.unsubscribeState('s', 'Room[0].SystemInfo.IPAddress', subHelpIPAddress);
    }

    /**
     * Initialize all the variables used in this module
     */
    function initializeVariables() {
        isCustomHelpActive = false;
        subHelpEnableCustomHelpPage = null;
        subHelpCustomHelpPageUrl = null;
        subHelpIPAddress = null;

        const avfConfigInfo = configModule.getUrls();
        uriProtocol = avfConfigInfo.uriProtocol;
        localIp = avfConfigInfo.ipAddress;
        ipAddress = avfConfigInfo.ipAddress;
        portNumber = avfConfigInfo.portNumber;
    }

    return {
        onInit,
        setIPAddress,
        setCustomHelpEnabled,
        showCustomHelpPage,
        isValidURL,
        setFallBackImageUrl
    };

}());