let admin_chat_ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
let protocol = window.location.protocol === "https:" ? "https" : "http";
let admin_chat_domain = "192.168.1.109:8000";
let userId = document.getElementById('userId').textContent.trim();
let osichatroomsSocket;
let osichatadminroomSocket;

function appendInnerConversationScript(div) {
    const innerConversationScript = document.createElement('script');
    innerConversationScript.type = 'text/javascript';
    innerConversationScript.src = `${protocol}://${admin_chat_domain}/static/js/osichat-admin/inner-conversation.js`;
    div.appendChild(innerConversationScript);
}

function getRooms(){
    osichatroomsSocket = new WebSocket(`${admin_chat_ws_scheme}://${admin_chat_domain}/ws/osichat/rooms/`);

    osichatroomsSocket.onopen = function () {
        console.log('WebSocket connection to rooms established');
        osichatroomsSocket.send(JSON.stringify({
            'event_type': 'set_client_type',
            'client_type': 'website_admin',
            'user_id': userId
        }));
    };

    osichatroomsSocket.onmessage = function (e) {
        const data = JSON.parse(e.data);
        const leftDiv = document.getElementById('widgetLeftSide');
        switch (data.event_type) {
            case 'get_chats':
                leftDiv.innerHTML = data.html;
                appendInnerConversationScript(leftDiv);
                break;
            case 'new_update':
                    const roomsContainer = document.getElementById('chatrooms');
                    const chatRoomDiv = roomsContainer.querySelector(`.chat-room[data-roomid='${data.chatroom_id}']`);
        
                    if (chatRoomDiv) {
                        chatRoomDiv.remove();  // Remove the existing chat room div
                    }
                    // Insert the new chat room HTML at the top of the container
                    const newChatRoomDiv = document.createElement('div');
                    newChatRoomDiv.innerHTML = data.html;
                    roomsContainer.insertAdjacentElement('afterbegin', newChatRoomDiv.firstElementChild);

                    appendInnerConversationScript(leftDiv);
                    break;
        
            default:
                console.log('Unknown event type:', data.event_type);
        }
    };

    osichatroomsSocket.onclose = function () {
        console.log('WebSocket connection to rooms closed');
    };

    osichatroomsSocket.onerror = function (error) {
        console.error('WebSocket error:', error);
    };
}

getRooms();