import requests, json
from mattermostdriver import Driver
import bridges

channels = {
    "ibfp3fskai8adgmynbfispz3se": 1125968295967850559, #comforter
    "rb43iupdy7rjbjwhg9w9c1mzjy": 954201387770736754, # lounge
    "s6muherhotfoircc1yzmwr5wty": 1119502004721557554,  # kweh
    "fkcqa3qj83gu3bfikcu55sfwww": 1367978276185964584, #misskey
    "na4doo5f83ykbc45m9a5dn513a": 1167176429797113926, #photos-from-another-star
    "9ydcz9orepbtmedncb7idh43hr": 1119508652844404816, #bulletin-board
    "81qmzfzeeif7mmfhpy7hkxnjuc": 955394194766192690 #photos-of-the-gang
}

users = {
    "f3nja8t9fpy73cxeh5ykzrozaw": 407247496008433675,
    "3byr3scix3f78xs5bpmgqzc6pc": 189202462442389514
}

async def event_handler(event):
    event = json.loads(event)
    if 'event' in event.keys() and event['event'] == "posted":
        print("event:", event)
        event_data = event['data']
        post = event_data['post']
        
        post = json.loads(post)
        if post['channel_id'] in channels.keys():
            print(f"watched channel {post['channel_id']}")
            if 'from_webhook' in post['props'].keys():
                is_webhook = post['props']['from_webhook']
            else:
                is_webhook = "false"
            print(is_webhook)
            if is_webhook != "true":
                # add file syncing means you need to get the "file_ids" key from the post and then download them into blobs and pass those along
                # to the request as files, on the discord side those files would then get attached to the webhook.

                user = mattermostDriver.users.get_user(user_id=post['user_id'])
                #print(user)
                post['user'] = user
                discord_id = None
                print("user:", user)
                if user['id'] in users.keys():
                    discord_id = users[post['user']['id']]
                post['discord_id'] = discord_id
                bridges.send_mattermost_to_discord(post, channel_to=channels[post['channel_id']])
            elif post['channel_id'] == "fkcqa3qj83gu3bfikcu55sfwww" and is_webhook == "true":
                username = post['props']['override_username']
                avatar_url = post['props']['override_icon_url']
                user = {"nickname": username}
                post['user'] = user
                post['discord_id'] = None
                bridges.send_mattermost_to_discord(post, channel_to=channels[post['channel_id']], avatar_url=avatar_url)

mattermostDriver = Driver({
    "url": "192.168.1.67",
    "port": 8065,
    "scheme": "http",
    "token": "dmefeb8t7pditf3ot9377hrxch"
})

mattermostDriver.login()
mattermostDriver.init_websocket(event_handler)
