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

    let availableFullDay = document.getElementById("availableAllDay");
    let availableWithInTime = document.getElementById("availableNext");
    let reserveNextTime = document.getElementById("reserveNext");
    let nextMeetingInfo = document.getElementById("nextMeetingInfo");
    let hasNextMeeting = false;
    let currentFormattedTime = '';
    let nextMeetingStartTimeAMPM = '';
    let currentMeetingEndTimeAMPM = '';
    let meetingInProgressStatus = false;
    let currentMeetingStartTimeAMPM = '';
    let isCalendaringConnected = false;
    let availableAllDay = false;
    let availableNextHr = document.getElementById('availableNextHr');
    let availableNextMin = document.getElementById('availableNextMin');
    let reserNextHr = document.getElementById('reserNextHr');
    let reserNextMin = document.getElementById('reserNextMin');
    let hrPostFix = `<span class="status-timer-unit align-middle vertical-align-center">hr</span>`;
    let minPostFix = `<span class="status-timer-unit align-middle vertical-align-center">min</span>`;
    let reserveNowEle = document.getElementById("reserveNow");
    let reserveNextEle = document.getElementById("reserveNextMeeting");
    let subMeetingStatusIsCalendaringConnected = null;
    let subMeetingStatusHasNextMeeting = null;
    let subMeetingStatusTimeFormattedAMPM = null;
    let subMeetingStatusStartTimeTimeFormattedAMPM = null;
    let subMeetingStatusEndTimeTimeFormattedAMPM = null;
    let subMeetingStatusMeetingInProgress = null;
    let subMeetingStatusCurrentMeetingTimeFormattedAMPM = null;
    let subMeetingStatusAvailableAllDay = null;

    /**
     * Calculate hours and minutes for next meeting
     */
    function meetingAvailabilityCalculation() {
        let currentTimeInMIlliSec = avfUtility.convertTime12tomilliSeconds(currentFormattedTime);
        let nextMeetingStartInMilliSec = avfUtility.convertTime12tomilliSeconds(nextMeetingStartTimeAMPM);
        let currentMeetingEndTimeAMPMInMilliSec = avfUtility.convertTime12tomilliSeconds(currentMeetingEndTimeAMPM);
        //  Difference between NextMeeting Start time and Now
        let hoursForNextAvailable = avfUtility.timeDiffInHHMM(nextMeetingStartInMilliSec, currentTimeInMIlliSec);
        // Difference between CurrentMeeting End time and Now
        let hoursForReserNext = avfUtility.timeDiffInHHMM(currentMeetingEndTimeAMPMInMilliSec, currentTimeInMIlliSec);
        meetingTimeContainerDisplay(hoursForNextAvailable, hoursForReserNext);
    }

    /**
     * Handle time calculation for next meeting
     * @param {object} hoursForNextAvailable
     * @param {object} hoursForReserNext
     */
    function meetingTimeContainerDisplay(hoursForNextAvailable, hoursForReserNext) {
        availableNextHr.style.display = hoursForNextAvailable.hour > 0 ? 'flex' : 'none';
        availableNextMin.style.display = parseInt(hoursForNextAvailable.minutes) > 0 ? 'flex' : 'none';
        reserNextHr.style.display = hoursForReserNext.hour > 0 ? 'flex' : 'none';
        reserNextMin.style.display = parseInt(hoursForReserNext.minutes) > 0 ? 'flex' : 'none';

        if (parseInt(hoursForNextAvailable.hour)) {
            let nextMeethours = avfUtility.zeroPad(hoursForNextAvailable.hour, 2);
            availableNextHr.innerHTML = `${nextMeethours} ${hrPostFix}`;
        }
        if (parseInt(hoursForNextAvailable.minutes)) {
            let nextMeetMinutes = avfUtility.zeroPad(hoursForNextAvailable.minutes % 60, 2);
            availableNextMin.innerHTML = `${nextMeetMinutes} ${minPostFix}`;
        }
        if (parseInt(hoursForReserNext.hour)) {
            let reservNextMeetHr = avfUtility.zeroPad(hoursForReserNext.hour, 2);
            reserNextHr.innerHTML = `${reservNextMeetHr} ${hrPostFix}`;
        }
        if (parseInt(hoursForReserNext.minutes)) {
            let reservNextMeetMinutes = avfUtility.zeroPad(hoursForReserNext.minutes % 60, 2);
            reserNextMin.innerHTML = `${reservNextMeetMinutes} ${minPostFix}`;
        }
    }

    /**
     * Onload of the screen
     */
    function onInit() {
        initializeVariables();
        // invokeUnsubscriptions();
        invokeSubscriptions();
    }

    /**
     * Invoke subscriptions related to module
     */
    function invokeSubscriptions() {
        CrComLib.subscribeState('b', 'Room[0].RoomScheduler.IsCalendaringConnected', (response) => {
            isCalendaringConnected = avfUtility.toBool(response);
            avfUtility.log("Room[0].RoomScheduler.IsCalendaringConnected", isCalendaringConnected);
            showMeetingStatus();
        });

        CrComLib.subscribeState('b', 'Room[0].RoomScheduler.HasNextMeeting', (response) => {
            hasNextMeeting = avfUtility.toBool(response);
            avfUtility.log(`Room[0].RoomScheduler.HasNextMeeting: ${hasNextMeeting}`);
            showMeetingStatus();
        });

        // TODO - check if below is valid as there is no Room[0]
        CrComLib.subscribeState('s', 'SystemTimeDate.TimeFormattedAMPM', (response) => {
            avfUtility.log(`current TimeFormattedAMPM: ${response}`);
            currentFormattedTime = response;
            showMeetingStatus();
        });

        CrComLib.subscribeState('s', 'Room[0].RoomScheduler.NextMeeting.StartTime.TimeFormattedAMPM', (response) => {
            avfUtility.log(`StartTime.TimeFormattedAMPM: ${response}`);
            nextMeetingStartTimeAMPM = response;
            showMeetingStatus();
        });

        CrComLib.subscribeState('s', 'Room[0].RoomScheduler.CurrentMeeting.EndTime.TimeFormattedAMPM', (response) => {
            avfUtility.log(`CurrentMeeting EndTime.TimeFormattedAMPM: ${response}`);
            currentMeetingEndTimeAMPM = response;
            showMeetingStatus();
        });

        CrComLib.subscribeState('b', 'Room[0].RoomScheduler.MeetingInProgress', (response) => {
            avfUtility.log(`Room[0].RoomScheduler.MeetingInProgress: ${response}`);
            meetingInProgressStatus = avfUtility.toBool(response);
            showMeetingStatus();
        });

        CrComLib.subscribeState('s', 'Room[0].RoomScheduler.CurrentMeeting.StartTime.TimeFormattedAMPM', (response) => {
            avfUtility.log(`Room[0].RoomScheduler.CurrentMeeting.StartTime.TimeFormattedAMPM: ${response}`);
            currentMeetingStartTimeAMPM = response;
            showMeetingStatus();
        });

        CrComLib.subscribeState('b', 'Room[0].RoomScheduler.AvailableAllDay', (response) => {
            avfUtility.log(`Room[0].RoomScheduler.AvailableAllDay: ${response}`);
            availableAllDay = avfUtility.toBool(response);
            showMeetingStatus();
        });
    }

    /**
     * Display the screen based on the status of the meeting
     */
    function showMeetingStatus() {
        meetingAvailabilityCalculation();
        availableFullDay.style.display = "block";
        nextMeetingInfo.style.display = "none";
        if (isCalendaringConnected) {
            document.getElementById('start-page-import-datetime').style.display = 'none';
            document.getElementById('start-page-import-scheduler').style.display = 'block';
            if (availableAllDay) {
                availableWithInTime.style.display = "none";
                reserveNextTime.style.display = "none";
            } else if (meetingInProgressStatus) {
                availableFullDay.style.display = "none";
                availableWithInTime.style.display = "none";
                reserveNextTime.style.display = "block";
            } else if (!meetingInProgressStatus) {
                availableFullDay.style.display = "none";
                availableWithInTime.style.display = "block";
                reserveNextTime.style.display = "none";
            }
            if (hasNextMeeting) {
                nextMeetingInfo.style.display = "block";
            }
        } else {
            document.getElementById('start-page-import-datetime').style.display = 'block';
            document.getElementById('start-page-import-scheduler').style.display = 'none';
        }
        const reRenderCustomLogo = false;
        dateTimeDisplayModule.dateTimeDisplay(reRenderCustomLogo);
    }

    /**
     * Publish the excute event.On basis of that event server config are getting updated
     */
    function bookNowMeetingRoom() {
        CrComLib.publishEvent('b', 'Room[0].RoomScheduler.ReserveNow.RecalculatedOptions.Execute', false);
        CrComLib.publishEvent('b', 'Room[0].RoomScheduler.ReserveNow.RecalculatedOptions.Execute', true);
        // bookNowRoom.show = true;
        navigationModule.openPopup(navigationModule.popupPages.scheduleMeetingImportPage);
    }

    /**
     * Invoke unsubscriptions related to module
     */
    function invokeUnsubscriptions() {
        CrComLib.unsubscribeState('b', 'Room[0].RoomScheduler.IsCalendaringConnected', subMeetingStatusIsCalendaringConnected);
        CrComLib.unsubscribeState('b', 'Room[0].RoomScheduler.HasNextMeeting', subMeetingStatusHasNextMeeting);
        CrComLib.unsubscribeState('s', 'SystemTimeDate.TimeFormattedAMPM', subMeetingStatusTimeFormattedAMPM);
        CrComLib.unsubscribeState('s', 'Room[0].RoomScheduler.NextMeeting.StartTime.TimeFormattedAMPM', subMeetingStatusStartTimeTimeFormattedAMPM);
        CrComLib.unsubscribeState('s', 'Room[0].RoomScheduler.CurrentMeeting.EndTime.TimeFormattedAMPM', subMeetingStatusEndTimeTimeFormattedAMPM);
        CrComLib.unsubscribeState('b', 'Room[0].RoomScheduler.MeetingInProgress', subMeetingStatusMeetingInProgress);
        CrComLib.unsubscribeState('s', 'Room[0].RoomScheduler.CurrentMeeting.StartTime.TimeFormattedAMPM', subMeetingStatusCurrentMeetingTimeFormattedAMPM);
        CrComLib.unsubscribeState('b', 'Room[0].RoomScheduler.AvailableAllDay', subMeetingStatusAvailableAllDay);
    }

    /**
     * Initialize all the variables used in this module
     */
    function initializeVariables() {
        subMeetingStatusIsCalendaringConnected = null;
        subMeetingStatusHasNextMeeting = null;
        subMeetingStatusTimeFormattedAMPM = null;
        subMeetingStatusStartTimeTimeFormattedAMPM = null;
        subMeetingStatusEndTimeTimeFormattedAMPM = null;
        subMeetingStatusMeetingInProgress = null;
        subMeetingStatusCurrentMeetingTimeFormattedAMPM = null;
        subMeetingStatusAvailableAllDay = null;
    }

    reserveNowEle.addEventListener('click', bookNowMeetingRoom, false);
    reserveNextEle.addEventListener('click', bookNowMeetingRoom, false);

    return {
        onInit: onInit
    }

}());