import asyncio
import websockets
import misskey
import json
import requests
from io import BytesIO
import bridges

MISSKEY_INSTANCE = "misskey.treehousefullofstars.com"
MISSKEY_TOKEN = "JSvVuz1eS2BGq6MagdQC9m109gOllwcO"

msk = misskey.Misskey(address=MISSKEY_INSTANCE, i=MISSKEY_TOKEN)
MY_ID = msk.i()['id']
WS_URL=f"wss://{MISSKEY_INSTANCE}/streaming"

channels = ['localTimeline', 'globalTimeline' 'hybridTimeline', 'main']


async def event_handler(event):
    event = json.loads(event)
    if event['body']['type'] == "note":
        bridges.send_misskey_to_mattermost(event, "fkcqa3qj83gu3bfikcu55sfwww")
        

async def connect_and_listen():
    while True:
        try:
            print("Connecting to WebSocket...")
            async with websockets.connect(WS_URL) as websocket:
                print("Connected to WebSocket")
                # Subscribe to the channels
                for channel in channels:
                    subscription_request = {
                        "type": "connect",
                        "body": {
                            "channel": channel,
                            "id": MY_ID,
                            "access_token": MISSKEY_TOKEN
                        }
                    }
                    await websocket.send(json.dumps(subscription_request))
                    print(f"Sent subscription request for {channel} channel with ID: {MY_ID}")
                    response = await websocket.recv()
                    print(f"Received response for {channel} channel: {response}")
                    await event_handler(response)
                # Listen for messages
                #while True:
                 #   async for message in websocket:
                  #      await handle_message(websocket, message)

        except websockets.exceptions.ConnectionClosedError as e:
            print(f"Connection closed unexpectedly: {e}")
            await asyncio.sleep(5)  # Wait for 5 seconds before retrying
        except Exception as e:
            print(f"An error occurred: {e}")
            await asyncio.sleep(5)  # Wait for 5 seconds before retrying

if __name__ == "__main__":
    asyncio.run(connect_and_listen())