import websocket
import json
import _thread
import time
import rel
from google import genai

username = "(insert username here)"
token = "(insert token here)"

def joinRoom(roomName):
    ws.send(json.dumps({
        "type": "joinRoom",
        "username": username,
        "token": token,
        "room": roomName,
        "content": ""
    }))

def sendMessage(content):
    ws.send(json.dumps({
        "type": "message",
        "username": username,
        "token": token,
        "content": content
    }))

def sendTyping(content):
    ws.send(json.dumps({
        "type": "typing",
        "username": username,
        "token": token,
        "content": content
    }))

def on_message(ws, message):
    print("Message received: " + message)
    if message == "ping":
        ws.send("pong")

def on_error(ws, error):
    print("Error:", error)

def on_close(ws, close_status_code, close_msg):
    print(f"Connection closed: {close_status_code} - {close_msg}")

def on_open(ws):
    print("Opening connection to Chookchat...")
    joinRoom("general")
    ws.send(json.dumps({
        "type": "connect",
        "username": username,
        "token": token,
        "content": username + " joined the room!"
    }))

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://bobcompass.online/api/websocket",
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close
                                )

    ws.run_forever(dispatcher=rel, reconnect=5, ping_interval=30, ping_timeout=10)
    rel.signal(2, rel.abort)
    rel.dispatch()
