const AutoLogout = function () {
    const redirectTo = '/PatientAccess/TransferLogout.aspx'; // URL to relocate the user to once they have timed out
    const keepAliveURL = '/PatientAccess/keepAlive.aspx'; // URL to call to keep the session alive
    const countdownId = 'secondsToBoom';
    const generalModal = new GeneralModal();

    let modalReference;

    function init() {
        window.running = false; // var to check if the countdown is running
        window.timer = null; // reference to the setInterval timer so it can be stopped
        
        // create the warning window and set autoOpen to false
        const dialogWindow = $("#sessionTimeoutWarning");

        const idleTime = $('#expiryTime', dialogWindow).val();
        const countdownTime = $('#countdownInSecond', dialogWindow).val();
        const header = $('#alertHeader', dialogWindow).html();
        const message = $('#alertMessage', dialogWindow).html();
        const cancelText = $('#cancelLinkText', dialogWindow).html();
        const cancelTool = $('#cancelLinkToolTip', dialogWindow).html();
        const confirmText = $('#logoutLinkText', dialogWindow).html();
        const confirmTool = $('#logoutLinkToolTip', dialogWindow).html();

        setupEventListeners();

        createCountdownWindow(
            dialogWindow,
            header,
            message,
            cancelText,
            cancelTool,
            confirmText,
            confirmTool,
            idleTime,
            countdownTime
        );
    }
    
    function setupEventListeners() {
        window.addEventListener('message', (event) => {
            if (event.data === 'ping') {
                // Reset or update the idle timer
                $(document).idleTimer('reset');
            }
        });
    }
    
    function createCountdownWindow(
        dialogWindow,
        header,
        message,
        cancelText,
        cancelTool,
        confirmText,
        confirmTool,
        idleTime,
        countdownTime
    ) {
        
        // Just for testing purposes
        // idleTime = 10000;

        const modalReference = generalModal.createAutoLogoutWindow(
            header,
            message,
            cancelText,
            confirmText,
            function () {
                // Redirect the user to the logout page
                window.location = redirectTo;
            },
            function () {
                $.idleTimer('pause'); // Pause the idle timer
            },
            function () {
                clearInterval(timer); // stop the timer
                running = false; // stop countdown

                // ajax call to keep the server-side session alive
                $.get(keepAliveURL).done(function() {
                    $.idleTimer('reset'); // reset the idle timer
                }) 
            }
        );

        $.ajax({
            type: "POST",
            url: "/PatientAccess/Services/AutoLogout.asmx/RefreshFormsAuthentication",
            data: "{}",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (msg) {
                if (msg.d) {
                    $.idleTimer({
                        timeout: parseInt(idleTime),
                        timerSyncId: "timeout-timer"
                    }); // start the idle timer
                }
            }
        });

        // bind to idleTimer's idle.idleTimer event
        $(document).on("idle.idleTimer", function (event, elem, obj) {
            // if the user is idle and a countdown isn't already running
            const isIdle = $(document).idleTimer("isIdle");
            if (isIdle && !running) {           

                running = true;

                //Get time when user was last active
                const diff = (+new Date()) - obj.lastActive - obj.timeout;

                if (diff >= countdownTime * 1000) {
                    window.location = redirectTo;
                } else {

                    modalReference.show();

                    const $countdownId = $(`#${countdownId}`);
                    $countdownId.html(Math.round(((countdownTime * 1000) - diff) / 1000));

                    var warningStart = (+new Date()) - diff;

                    timer = setInterval(function () {
                        const remaining = Math.round((countdownTime) - (((+new Date()) - warningStart) / 1000));

                        if (remaining >= 0) {
                            $countdownId.html(remaining);
                        } else {
                            modalReference.hide();
                            window.location = redirectTo;
                        }
                    }, 1000)
                }
            }
        });
    }
    
    return {
        init: init
    };
}

$(document).ready(function () {
    const autoLogout = new AutoLogout();
    autoLogout.init();
});

// Path: DoctorAccess/PatientAccess/Includes/Scripts/PA2.0/autologout.js