const IDLE_TIME_LIMIT = 5 * 60 * 1000;

// Set the timer variable to null
let idleTimer = null;

// Function to reset the idle timer
function resetIdleTimer() {
    // Clear the previous timer if it exists
    if (idleTimer) {
        clearTimeout(idleTimer);
    }

    // Start a new timer
    idleTimer = setTimeout(logoutUser, IDLE_TIME_LIMIT);
}

// Add event listeners to reset the idle timer on user activity
document.addEventListener('mousemove', resetIdleTimer);
document.addEventListener('mousedown', resetIdleTimer);
document.addEventListener('keypress', resetIdleTimer);
document.addEventListener('touchstart', resetIdleTimer);
document.addEventListener('scroll', resetIdleTimer);

// Function to log out the user
function logoutUser() {
    localStorage.removeItem("userObj");
    localStorage.removeItem("currentRole");
    window.location.href + '?eraseCache=true';
    window.location = "login.html";
    location.reload(true);
    window.location.reload();
    localStorage.clear();
    window.location.reload();

}

// Start the idle timer on page load
resetIdleTimer();

$(window).on('beforeunload', function() {
    // Append a cache-busting parameter to all resource URLs
    $('img, script, link[rel="stylesheet"]').each(function() {
        var originalUrl = $(this).attr('src') || $(this).attr('href');
        if (originalUrl) {
            var cacheBustUrl = originalUrl + '?cache=' + Date.now();
            $(this).attr('src', cacheBustUrl);
        }
    });
});



if ('caches' in window) {
    caches.keys().then(function(cacheNames) {
        cacheNames.forEach(function(cacheName) {
            caches.delete(cacheName);
        });
    });
}


function clearCache() {
    // if (confirm("Clearing the cache will delete temporary files and may affect your browsing experience. Are you sure you want to clear the cache?")) {
    if ('caches' in window) {
        caches.keys().then(function(cacheNames) {
            cacheNames.forEach(function(cacheName) {
                caches.delete(cacheName);
            });
        });
    }
    // alert("Cache cleared successfully.");
    // }
}


