var inactivityTime = function () {
    var timeOutValue = $("#timeout").val()
    var remindTimeValue = $("#remindTime").val()
    var externalUrl = $("#externalUrl").val()
    var remindTime;
    var timeOut;

    function logout() {
        location.href = externalUrl + '/signout'
    }

    function checkPlayMedia(element) {
        element.addEventListener('play', stopSessionTimeOut, true)
        element.addEventListener('pause', resetTimeOutWarning, true)
        if (element.paused) {
            resetTimeOutWarning()
        }
    }
    
    function stopSessionTimeOut() {
        clearTimeout(remindTime);
        clearTimeout(timeOut);
    }
    
    function resetTimeOutWarning() {
        clearTimeout(remindTime);
        remindTime = setTimeout(showTimeoutWarning, (timeOutValue - remindTimeValue) * 1000, true)
    }
    
    function showTimeoutWarning() {
        $('#timeoutWarning').modal('show')
    }
    
    resetTimeOutWarning()
    $('#timeoutWarning').on('shown.bs.modal', function () {
        timeOut = setTimeout(logout, remindTimeValue * 1000, true)
    })
    
    var resetTimeElement = document.getElementById('resetTimeBtn');
    resetTimeElement.addEventListener('click', function() {
        clearTimeout(timeOut)
        resetTimeOutWarning()
    });
    
    window.addEventListener('load', resetTimeOutWarning, true);
    var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
    
    const iframes = document.querySelectorAll('iframe');
    iframes.forEach(iframe => {
        const iframeDocument = iframe.contentWindow.document;
        events.forEach(name => {
            iframeDocument.addEventListener(name, () => {
                resetTimeOutWarning()
            }, true);
        });
    });

    events.forEach(function (name) {
        document.addEventListener(name, function() {
            const audio = document.querySelector('audio')
            const video = document.querySelector('video')
            if(audio || video) {
                checkPlayMedia(audio ? audio : video)
            } else {
                resetTimeOutWarning()
            }
        }, true);
    });
};

window.onload = function () {
    inactivityTime();
}
