// WebSocket connection for new statuses
const ws_protocol = window.location.protocol === "https:" ? "wss" : "ws";
const newStatusesTimeSocketUrl = `${ws_protocol}://${window.location.host}/ws/update-statuses-time/`;
const newStatusesTimeSocket = new WebSocket(newStatusesTimeSocketUrl);

newStatusesTimeSocket.onopen = () => {
    console.log('WebSocket connection to new statuses time established');
    
    function sendUpdate() {
        newStatusesTimeSocket.send(JSON.stringify({ 'event_type': 'update_statuses_time' }));
    }

    // Call sendUpdate every 1 minute (60000 milliseconds)
    setInterval(sendUpdate, 60000);
    // Call it immediately on load
    sendUpdate();
};

newStatusesTimeSocket.onmessage = function(e) {
    const data = JSON.parse(e.data);

    if (data.event_type === 'update_statuses_time') {
        const activityDiv = document.getElementById('activitiesContainer');
        activityDiv.innerHTML = data.html;

        // Update user activity containers based on online status
        const onlineUsersIds = data.online_users_ids || [];
        const userActivityContainers = document.querySelectorAll(".users-activities");

        userActivityContainers.forEach(container => {
            const userId = container.getAttribute("data-userId");

            if (onlineUsersIds.map(id => id.toString()).includes(userId)) {
                container.querySelector("#connected").classList.remove("hidden");
                container.querySelector("#not-connected").classList.add("hidden");
            } else {
                container.querySelector("#connected").classList.add("hidden");
                container.querySelector("#not-connected").classList.remove("hidden");
            }
        });
    }
};

newStatusesTimeSocket.onclose = () => {
    console.log('WebSocket connection to new statuses time closed');
};

newStatusesTimeSocket.onerror = (error) => {
    console.log('WebSocket error:', error);
};
