function extractPageFromUrl(url) {
    // Match /page/<page> pattern
    const match = url.match(/\/page\/([^\/]+)/);
    return match ? match[1] : null;
}

$(document).ready(() => {
    pageActivator();
});

htmx.onLoad(function(content) {
    pageActivator();
});

var deactivator = () => {};
var currentPage = "";

function pageActivator(){
    const currentPath = window.location.pathname;
    var newPage = extractPageFromUrl(currentPath);
    
    if(newPage == currentPage){
        return;
    }

    console.log(`Swapping from ${currentPage} to ${newPage}`);
    currentPage = newPage;

    // Deactivate the old page
    deactivator();

    switch (currentPage) {
        case 'activities':
            deactivator = activitiesPage();
            break;
        default:
            break;
    }
}

function activitiesPage() {

    function showLive(number, domElement) {
        if(!domElement){
            domElement = $('#rsvp-activity .live');
        }
        
        if(domElement && number){
            switch (number) {
                case 0:
                case 1:
                    domElement.html("🔴 Only you");
                    break;
                case 2:
                    domElement.html("🔴 One other is watching");
                    break;
                default:
                    domElement.html("🔴 " + --number + " others are watching");
                    break;
            }
        }
    }

    const activitySocket = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/event/'
        + eventId
        + '/'
    );

    var globalLiveConnected = 0;

    $("body").on("htmx:load.activities", function(evt) {
        console.info("HTMX OnLoad ...");
        var domElement = $(evt.detail.elt.querySelector(".live"));
        showLive(globalLiveConnected, domElement);
    });

    activitySocket.onmessage = function(e) {
        var data = JSON.parse(e.data);

        if(data.connected){
            globalLiveConnected = data.connected;
            showLive(globalLiveConnected);
        }

        // We caused the change, ignore
        if(rsvpId && data.rsvp && rsvpId == data.rsvp){
            return;
        }

        // Activity attendees (when everyone can join)
        const attendees = $('#activity-' + data.activity + ' .numatt');
        if(attendees !== null && data.attendees !== null){
            attendees.html(data.attendees);
        }

        // Activity capacity (when there is a guest limit)
        const capacity = $('#activity-' + data.activity + ' .numcap');
        const fullwarn = $('#activity-' + data.activity + ' .full-warning');
        if(capacity !== null && data.capacity !== null){
            capacity.html(data.capacity);

            if(data.capacity == 0){
                fullwarn.removeClass("hidden");
            } else {
                fullwarn.addClass("hidden");
            }
        }

        // Activity capacity (when there is a guest limit)
        const activity = $('#activity-' + data.activity);
        const spacewarn = $('#activity-' + data.activity + ' .space-warning');
        if(activity !== null && data.capacity !== null){
            if(!(activity.hasClass("attending"))){
                if(data.capacity >= guestCount){
                    activity.removeClass("bg-gray bd-gray");
                    spacewarn.addClass("hidden");
                }
                else{
                    activity.addClass("bg-gray bd-gray");
                    spacewarn.removeClass("hidden");
                }
            }
        }

        // Activity capacity (when there is a guest limit)
        const attendees_names = $('#activity-' + data.activity + ' .stratt');
        if(attendees_names !== null){
            html = "";

            for(index in data.guests){
                html += "<span class='badge bg-blue'>" + data.guests[index].join(", ") + "</span>";
            }

            attendees_names.html(html);
        }
    };

    activitySocket.onopen = function(e) {
        console.info('Activity socket opened');
    };

    activitySocket.onclose = function(e) {
        console.error('Activity socket closed unexpectedly');
    };

    activitySocket.onerror = function(e) {
        console.error('Activity socket had unexpected error');
    };

    return (() => {
        $("body").off("htmx:load.activities");
        activitySocket.close();
    });
};



