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

    let time;
    let initializing = false;
    let screenSaverEnabled = false;
    let customSSEnabled = false;
    let sleepTime = 3;
    let bgRefreshRate = "10";
    let bgUrlList = '';
    let screenSaverBackGround = document.getElementById("screenSaverBg");

    let uriProtocol = "";
    let localHostWebViewIp = "";
    let portNumber = "";

    let imageIpAddress = '';
    let localImageList = ['/img/bg01_1066x600.png', '/img/bg02_1066x600.png', '/img/bg03_1066x600.png',
        '/img/bg04_1066x600.png', '/img/bg05_1066x600.png', '/img/bg06_1066x600.png'
    ];
    let screenSaverStartTime = 0;
    let screenSaverEndTime = 0;
    let customBackgroundUrls = [];
    let defaultBackgroundUrls = "";
    let blankBackgroundUrls = "./app/project/assets/img/black.jpg";
    let subScreensaverBackgroundsInterval = null;
    let subScreensaverScreenSaverSleepTime = null;
    let subScreensaverScreenSaverEnabled = null;
    let subScreensaverScreenSaverStartTime = null;
    let subScreensaverScreenSaverEndTime = null;
    let subScreensaverEnableCustomSSBackground = null;
    let subScreensaverCustomSSBackgroundUrls = null;
    let subScreensaverIPAddress = null;

    /**
     * Initialize screensaver with initial state
     * @param {boolean} initFlag
     */
    function onInit() {
        initializeVariables();
        // invokeUnsubscriptions();
        invokeSubscriptions();
    }

    /**
     * Invoke subscriptions related to module
     */
    function invokeSubscriptions() {
        subScreensaverBackgroundsInterval = CrComLib.subscribeState('n', 'Room[0].TouchScreenSettings.BackgroundsInterval', (response) => {
            avfUtility.log('TouchScreenSettings.BackgroundsInterval: ' + response);
            setRefreshRate(response);
        });

        subScreensaverScreenSaverSleepTime = CrComLib.subscribeState('n', 'Room[0].TouchScreenSettings.ScreenSaverSleepTime', (response) => {
            avfUtility.log('TouchScreenSettings.ScreenSaverSleepTime: ' + response);
            setSleepTime(response);
        });

        subScreensaverScreenSaverEnabled = CrComLib.subscribeState('b', 'Room[0].TouchScreenSettings.ScreenSaverEnabled', (response) => {
            avfUtility.log('TouchScreenSettings.ScreenSaverEnabled: ' + response);
            setScreenSaverEnabled(avfUtility.toBool(response));
        });

        subScreensaverScreenSaverStartTime = CrComLib.subscribeState('n', 'Room[0].TouchScreenSettings.ScreenSaverStartTime', (response) => {
            avfUtility.log('TouchScreenSettings.ScreenSaverStartTime: ' + response);
            setScreenSaverStartTime(response);
        });

        subScreensaverScreenSaverEndTime = CrComLib.subscribeState('n', 'Room[0].TouchScreenSettings.ScreenSaverEndTime', (response) => {
            avfUtility.log('TouchScreenSettings.ScreenSaverEndTime: ' + response);
            setScreenSaverEndTime(response);
        });

        subScreensaverEnableCustomSSBackground = CrComLib.subscribeState('b', 'Room[0].TouchScreenSettings.EnableCustomSSBackground', (response) => {
            avfUtility.log('TouchScreenSettings.EnableCustomSSBackground: ' + response);
            setCustomSSEnabled(avfUtility.toBool(response));
        });

        subScreensaverCustomSSBackgroundUrls = CrComLib.subscribeState('s', 'Room[0].TouchScreenSettings.CustomSSBackgroundUrls', (response) => {
            avfUtility.log('TouchScreenSettings.CustomSSBackgroundUrls: ' + response);
            setCustomSSBackgroundUrls(response);
        });

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

    /**
     * Invoke unsubscriptions related to module
     */
    function invokeUnsubscriptions() {
        CrComLib.unsubscribeState('n', 'Room[0].TouchScreenSettings.BackgroundsInterval', subScreensaverBackgroundsInterval);
        CrComLib.unsubscribeState('n', 'Room[0].TouchScreenSettings.ScreenSaverSleepTime', subScreensaverScreenSaverSleepTime);
        CrComLib.unsubscribeState('b', 'Room[0].TouchScreenSettings.ScreenSaverEnabled', subScreensaverScreenSaverEnabled);
        CrComLib.unsubscribeState('n', 'Room[0].TouchScreenSettings.ScreenSaverStartTime', subScreensaverScreenSaverStartTime);
        CrComLib.unsubscribeState('n', 'Room[0].TouchScreenSettings.ScreenSaverEndTime', subScreensaverScreenSaverEndTime);
        CrComLib.unsubscribeState('b', 'Room[0].TouchScreenSettings.EnableCustomSSBackground', subScreensaverEnableCustomSSBackground);
        CrComLib.unsubscribeState('s', 'Room[0].TouchScreenSettings.CustomSSBackgroundUrls', subScreensaverCustomSSBackgroundUrls);
        CrComLib.unsubscribeState('s', 'Room[0].SystemInfo.IPAddress', subScreensaverIPAddress);
    }

    /**
     * Initialize all the variables used in this module
     */
    function initializeVariables() {
        initializing = false; // TODO
        turnOffScreenSaver();
        screenSaverEnabled = false;
        customSSEnabled = false;
        customBackgroundUrls.length = 0;
        defaultBackgroundUrls = "";
        subScreensaverBackgroundsInterval = null;
        subScreensaverScreenSaverSleepTime = null;
        subScreensaverScreenSaverEnabled = null;
        subScreensaverScreenSaverStartTime = null;
        subScreensaverScreenSaverEndTime = null;
        subScreensaverEnableCustomSSBackground = null;
        subScreensaverCustomSSBackgroundUrls = null;
    }

    /**
     * Get the IP address value
     * @param {string} value
     */
    function setIPAddress(value) {
        imageIpAddress = value.trim();
        constructLocalBgUrls();
    }

    /**
     * Set the the custom config enable state
     * @param {boolean} value
     */
    function setCustomSSEnabled(value) {
        customSSEnabled = value;
        resetTimer();
    }

    /**
     * Set the screensaver enable state
     * @param {boolean} value
     */
    function setScreenSaverEnabled(value) {
        screenSaverEnabled = value;
        resetTimer();
    }

    /**
     * Set the screensaver start time
     * @param {string} value 
     */
    function setScreenSaverStartTime(value) {
        screenSaverStartTime = value;
    }

    /**
     * Set the screensaver end time
     * @param {string} value
     */
    function setScreenSaverEndTime(value) {
        screenSaverEndTime = value;
    }

    /**
     * Set the sleeptime for screensaver. Screensaver started displaying when panel is inactive more then sleep time
     * @param {string} value
     */
    function setSleepTime(value) {
        if (!!value && !isNaN(value)) {
            sleepTime = parseInt(value);
            resetTimer();
        }
    }

    /**
     * Set refreshrate interval for screen saver background images
     * @param {string} value
     */
    function setRefreshRate(value) {
        if (!!value && !isNaN(value)) {
            bgRefreshRate = '' + value;
        }
        if (!!screenSaverBackGround) {
            screenSaverBackGround.setAttribute("refreshrate", bgRefreshRate);
        }
    }

    function validateAndUpdateImageUrl(urls) {
        let imageUrls = urls.split("|");
        for (let i = 0; i < imageUrls.length; i++) {
            // promises.push(helpModule.isValidURL(imageUrls[i]));
            helpModule.isValidURL(imageUrls[i]).then(
                function fulfilled(img) {
                    imageUrls[i] = img;
                    customBackgroundUrls[i] = imageUrls[i];
                    avfUtility.log("Approved customBackgroundUrls[i]", customBackgroundUrls[i]);
                },
                function rejected() {
                    customBackgroundUrls[i] = helpModule.setFallBackImageUrl();
                    avfUtility.log("Rejected customBackgroundUrls[i]", customBackgroundUrls[i]);
                }

            );
        }

    }
    /**
     * Create list of default image urls when screen saver images not provided by user
     */
    function constructLocalBgUrls() {
        const avfConfigInfo = configModule.getUrls();
        uriProtocol = avfConfigInfo.uriProtocol;
        localHostWebViewIp = avfConfigInfo.ipAddress;
        portNumber = avfConfigInfo.portNumber;

        let imageUrls = '';
        if (imageIpAddress === localHostWebViewIp) {
            imageIpAddress = "localhost";
        }
        let ipAddress = imageIpAddress.split(":")[0];
        imageIpAddress = ipAddress + portNumber;
        let newLocalImgess = localImageList.map((item) => {
            let imageUrl = `${uriProtocol}${imageIpAddress}${item}`;
            return imageUrl;
        });
        imageUrls = newLocalImgess.join(" | ");
        defaultBackgroundUrls = imageUrls;
    }

    /**
     * Create list of default image urls
     * @param {string} value list of image urls 
     */
    function setCustomSSBackgroundUrls(value) {
        if (value) {
            let newStr = value.trim().replace(/,{1,}$/, '');
            bgUrlList = newStr.replace(/,/g, ' | ');
            validateAndUpdateImageUrl(bgUrlList);
        }
        resetTimer();
    }

    /**
     * Get the time difference from midnight to the current time
     */
    function getMinutesSinceMidnight() {
        let now = new Date(),
            then = new Date(
                now.getFullYear(),
                now.getMonth(),
                now.getDate(),
                0, 0, 0),
            diff = now.getTime() - then.getTime();
        return diff / 60000;
    }

    /**
     * Show the screensaver and set the background url
     */
    function showScreenServer() {
        let now = getMinutesSinceMidnight();
        // Check if within screen saver start/end time 
        // if (screenSaverEnabled === true && initializing === false && (
        //     (screenSaverStartTime < now && screenSaverEndTime > now) ||
        //     (screenSaverStartTime < now && screenSaverEndTime < now && screenSaverEndTime < screenSaverStartTime)
        // )) {
        //     setTimeout(() => {
        //         navigationModule.openPopup(navigationModule.popupPages.screensaverImportPage);
        //     }, 1000);
        // }
        avfUtility.log("showScreenServer screenSaverBackGround", screenSaverBackGround);
        if (screenSaverBackGround) {
            avfUtility.log("showScreenServer customSSEnabled", customSSEnabled);
            avfUtility.log("showScreenServer customBackgroundUrls", customBackgroundUrls);
            avfUtility.log("showScreenServer defaultBackgroundUrls", defaultBackgroundUrls);
            if ((screenSaverEnabled === true &&
                (screenSaverStartTime < now && screenSaverEndTime > now) ||
                (screenSaverStartTime < now && screenSaverEndTime < now && screenSaverEndTime < screenSaverStartTime)
            ) ){
                if (customSSEnabled) {
                    screenSaverBackGround.url = customBackgroundUrls.join(" | ");
                } else {
                    screenSaverBackGround.url = defaultBackgroundUrls;
                }
            } else {
                screenSaverBackGround.url = blankBackgroundUrls;
            }
            avfUtility.log("showScreenServer screenSaverBackGround.url", screenSaverBackGround.url);
        }
        if (initializing === false) {
            setTimeout(() => {
                navigationModule.openPopup(navigationModule.popupPages.screensaverImportPage);
            }, 1000);
        }
    }

    /**
     * Reset the sleep timer when panel is active
     */
    function resetTimer() {
        navigationModule.closePopup(navigationModule.popupPages.screensaverImportPage);
        clearTimeout(time);
        // Commenting if condition because of the fix for AVFRM-2388
        // if (screenSaverEnabled) {
            time = window.setTimeout(showScreenServer, sleepTime * 1000);
        // }
    }

    /**
     * Hide the screen saver display
     */
    function turnOffScreenSaver() {
        navigationModule.closePopup(navigationModule.popupPages.screensaverImportPage);
    }

    // TODO: Use touch activity instead (app.js). Currently only works for x60 panels
    let events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'touchmove'];
    events.forEach(function (name) {
        document.addEventListener(name, resetTimer, true);
    });

    return {
        onInit,
        setIPAddress,
        turnOffScreenSaver,
        resetTimer
    };

}());