import requests, re
from mattermostdriver import Driver
from bs4 import BeautifulSoup
from io import BytesIO

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

mattermostDriver.login()


def parse_links_from_mattermost(string):
    linkmatches = re.compile(r'\((https?://[^\s)]+)\)')
    fullmatches = re.compile(r'!\[.*?\]\(.*?\)')

    links = linkmatches.findall(string)
    full = fullmatches.findall(string)

    for match in full:
        string = string.replace(match, "")

    for match in links:
        string += match

    return string


DISCORD_BOT_URL = 'http://localhost:5001/post_message'

def getDiscordUserProfile(discord_user_id):
    print("test")
    bot_token = "MTMyNzcxNDM3MTEyMzgxMDMwNA.GwLjEd.quGP0FA5gHRe1xLyuYq-ANuJ5cRuRQ6dhJiojI"
    guild_id = "954201387770736751"
    headers = {'Authorization': f'Bot {bot_token}'}
    discord_guild_endpoint = f"https://discord.com/api/v10/guilds/{guild_id}/members/{discord_user_id}"
    response = requests.get(discord_guild_endpoint, headers=headers)
    print(response)
    if response.status_code == 200:
        discord_user = response.json()
        username = discord_user['nick']
        if discord_user['avatar']:
            avatar_url = f"https://cdn.discordapp.com/guilds/{guild_id}/users/{discord_user['user']['id']}/avatars/{discord_user['avatar']}.png"
        else:
            avatar_url = f"https://cdn.discordapp.com/avatars/{discord_user['user']['id']}/{discord_user['user']['avatar']}.png"
        return True, username, avatar_url
    else:
        return False, "Unknown", ""

def send_mattermost_to_discord(post, webhook_url, avatar_url=""):
    
    post_message = parse_links_from_mattermost(post['message'])

    username = "Unknown"
    if post['user']['nickname'] == "":
        username = post['user']['username']
    else:
        username = post['user']['nickname'] 
    
    payload = {
        "content": post_message,
        "username": username,
        "avatar_url": avatar_url
    }

    response = requests.post(webhook_url, data=payload)
    print("webhook response: ", response)
    if response.status_code == 204:
        print("Message sent successfully.")
    else:
        print("Failed to send the message.")
        print(response.text)

def parse_links_from_discord(string):
    linkmatches = re.compile(r'\bhttps?://(?:tenor|giphy)\.com/\S+\b')
    links = linkmatches.findall(string)

    for match in links:
        response = requests.get(match)
        soup = BeautifulSoup(response.text, 'html.parser')
        gif_title = soup.find('meta', property='og:title')['content']
        gif_url = soup.find('meta', property='og:image')['content']

        string = string.replace(match, "")
        string += f"![{gif_title}]({gif_url})"

    return string

def send_discord_to_mattermost(message, channel_to):
    channel_id = mattermostDriver.channels.get_channel_by_name_and_team_name(channel_to[1], channel_to[0])['id']
    new_contents = ""
    count = 0
    file_ids = []

    if message.attachments:
        for attachment in message.attachments:
            file_url = attachment.url

            response = requests.get(file_url)
            file_data = response.content

            file_id = mattermostDriver.files.upload_file(
                channel_id=channel_id,
                files={'files': (attachment.filename, file_data)}
            )['file_infos'][0]['id']
            file_ids.append(file_id)
    
    text = message.content
    if count>0:
        text += new_contents

    text = parse_links_from_discord(text)

    response = mattermostDriver.posts.create_post(options={
        'channel_id': channel_id,
        'props':{
            'from_webhook': 'true',
            'override_username': message.author.nick, 
            'override_icon_url': message.author.display_avatar.url
            },
        'message': text,
        'file_ids': file_ids})
    
def send_misskey_to_mattermost(event, channel_id):
    if event['body']['body']['renoteId']:
        files = event['body']['body']['renote'].get('files', None)
    else:
        files = event['body']['body'].get('files', None)

    file_ids=[]
    if files != []:
        for i, file in enumerate(files):
            response = requests.get(file['url'])
            file_data = BytesIO(response.content)
            filename = file['name']
            file_id = mattermostDriver.files.upload_file(
                channel_id=channel_id,
                files={'files': (filename, file_data)}
            )['file_infos'][0]['id']
            file_ids.append(file_id)
    
    if event['body']['body']['renoteId']:
        renote_user = event['body']['body']['renote']['user'].get('name', 'unknown')
        renote_username = event['body']['body']['renote']['user'].get('username', 'unknown')
        renote_user_host = event['body']['body']['renote']['user'].get('hose', 'unknown')
        note_content = f"*Renoted {renote_user} (@{renote_username}@{renote_user_host})*\n{event['body']['body']['renote']['text']}"
    else:
        note_content = event['body']['body'].get('text', 'No text in note')

    username = event['body']['body']['user'].get('name', 'Misskey Bot')
    avatar_url = event['body']['body']['user'].get('avatarUrl', '')

    response = mattermostDriver.posts.create_post(options={
    'channel_id': channel_id,
    'props':{
        'from_webhook': 'true',
        'override_username':username, 
        'override_icon_url': avatar_url
        },
    'message': note_content,
    'file_ids': file_ids})


owncast_webhook = "https://chat.treehousefullofstars.com/hooks/3o9tozzipi8e3rtkcns63pesfr"
def send_owncast_to_mattermost(event):
    print(event)
    data = event['eventData']
    type = event['type']
    post = False
    text = ""

    if type == "STREAM_STARTED":
        text = f"Stream Starting... {data['streamTitle']}\n<http://184.83.153.182:5000/stream>"
        post = True
    elif type == "STREAM_STOPPED":
        text = f"Stream Stopping..."
        post = True
    elif type == "STREAM_TITLE_UPDATED":
        text = f"Stream title changed! We are now streaming... {data['streamTitle']}"
        post = True

    if post:
        payload = {
            "text": text,
            "username": f"{data['name']} - Stream",
            "icon_url": "http://192.168.1.67:8086/logo"
        }
        requests.post(owncast_webhook, json=payload)