const wsScheme = window.location.protocol === "https:" ? "wss" : "ws";
const protocol = window.location.protocol === "https:" ? "https" : "http";
const osinaDomain = "osina.ositcom.com";
const ositcomDomain = "ositcom.com";


async function fetchClientData() {
    let clientData = { client_ip: 'Unknown', client_country: 'Unknown' };
    while (clientData.client_ip === 'Unknown') {
        try {
            const response = await fetch(`${protocol}://${osinaDomain}/get-client-ip/`);
            const data = await response.json();
            if (data.ip) {
                clientData = {
                    client_ip: data.ip,
                    client_country: data.country || 'Unknown',
                    client_region: data.region || '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(`${protocol}://${ositcomDomain}/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;
}



const getBrowserInfo = () => {
    const userAgent = navigator.userAgent;
    let browserName = "Unknown";
    let osName = "Unknown";

    if (userAgent.indexOf("Firefox") > -1) {
        browserName = "Firefox";
    } else if (userAgent.indexOf("SamsungBrowser") > -1) {
        browserName = "Samsung Internet";
    } else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) {
        browserName = "Opera";
    } else if (userAgent.indexOf("Trident") > -1) {
        browserName = "Internet Explorer";
    } else if (userAgent.indexOf("Edge") > -1) {
        browserName = "Edge";
    } else if (userAgent.indexOf("Chrome") > -1) {
        browserName = "Chrome";
    } else if (userAgent.indexOf("Safari") > -1) {
        browserName = "Safari";
    }

    if (userAgent.indexOf("Win") > -1) {
        osName = "Windows";
    } else if (userAgent.indexOf("Mac") > -1) {
        osName = "MacOS";
    } else if (userAgent.indexOf("X11") > -1) {
        osName = "UNIX";
    } else if (userAgent.indexOf("Linux") > -1) {
        osName = "Linux";
    } else if (userAgent.indexOf("Android") > -1) {
        osName = "Android";
    } else if (userAgent.indexOf("like Mac") > -1) {
        osName = "iOS";
    }

    return { browserName, osName };
};


async function initializeVisitorsWebSocket() {

    const referrer = document.referrer;
    const clientData = await fetchClientData();
    const session_id = await fetchVisitorsSession();
    const browserInfo = getBrowserInfo();
    const visitorsSocketUrl = `${wsScheme}://${osinaDomain}/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,
            'title': window.document.title,
            'client_ip': clientData.client_ip,
            'client_country': clientData.client_country,
            'client_region': clientData.client_region,
            'browser_name': browserInfo.browserName,
            'os_name': browserInfo.osName,
            '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);
    };

    window.addEventListener('offline', () => {
        if (visitorsSocket) {
            visitorsSocket.close();
        }
    });
}


initializeVisitorsWebSocket();