const visitors_ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
const my_domain = "192.168.1.109:8000";

async function fetchClientData() {
    let clientData = { client_ip: 'Unknown', client_country: 'Unknown' };
    while (clientData.client_ip === 'Unknown') {
        try {
            const response = await fetch('http://192.168.1.109:8000/get-client-ip/');
            const data = await response.json();
            if (data.ip) {
                clientData = {
                    client_ip: data.ip,
                    client_country: data.country || 'Unknown'
                };
            }
        } catch (error) {
            console.error('Error fetching client data:', error);
        }
    }
    return clientData;
}


async function fetchVisitorsSession() {
    let session_id = 'Unknown';
    while (session_id === 'Unknown') {
        try {
            const response = await fetch('http://192.168.1.109:3000/get-client-session/');
            const data = await response.json();
            if (data.session_id) {
                session_id = data.session_id;
            }
        } catch (error) {
            console.error('Error fetching session ID:', error);
        }
    }
    return session_id;
}

async function initializeVisitorsWebSocket() {

    const referrer = document.referrer;
    const clientData = await fetchClientData();
    const session_id = await fetchVisitorsSession();
    const visitorsSocketUrl = `${visitors_ws_scheme}://${my_domain}/ws/osichat/visitors/`;
    const visitorsSocket = new WebSocket(visitorsSocketUrl);

    visitorsSocket.onopen = () => {
        console.log('WebSocket connection to visitors established');

        const event_message = {
            'event_type': 'visitor_ping',
            'referrer': referrer,
            'url': window.location.href,
            'client_ip': clientData.client_ip,
            'client_country': clientData.client_country,
            'session_id': session_id
        };
        visitorsSocket.send(JSON.stringify(event_message));
    };

    visitorsSocket.onclose = () => {
        console.log('WebSocket connection to visitors closed');
    };

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


initializeVisitorsWebSocket();