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 send_mattermost_to_discord(post, channel_to, avatar_url=None):
    
    post_message = parse_links_from_mattermost(post['message'])

    username = "Unknown"
    if post['user']['nickname'] == "":
        username = post['user']['username']
    else:
        username = post['user']['nickname']

    if avatar_url:
        payload = {
            "message": post_message,
            "channel_to": channel_to,
            "username": username,
            "avatar_url": avatar_url,
            "discord_id": post['discord_id']
        } 
    else:
        payload = {
            "message": post_message,
            "channel_to": channel_to,
            "username": username,
            "avatar_url": None,
            "discord_id": post['discord_id']
        }    
    
    response = requests.post(DISCORD_BOT_URL, json=payload)
    
    if response.status_code == 200:
        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):
    bearer_token = "g9rpuzcpkpgyddozad6j5nui9r"
    url = "http://chat.treehousefullofstars.com/api/v4/posts"
    webhook_url = "https://chat.treehousefullofstars.com/hooks/qjxs466x1pr63y71bszze56x4c"
    
    channel_id = mattermostDriver.channels.get_channel_by_name_and_team_name('Treehousefullofstars', channel_to)['id']

    new_contents = ""
    count = 0
    file_ids = []
    """if message.embeds:
        print(message.embeds)
        for embed in message.embeds:
            new_contents += f"\n{embed.url}"
            count += 1
            
            file_url = embed.url

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

            file_id = mattermostDriver.files.upload_file(
                channel_id=channel_id,
                files={'files': (embed.filename, file_data)}
            )['file_infos'][0]['id']
            file_ids.append(file_id)"""

    if message.attachments:
        print(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)
    

    """payload = {
        "channel": channel_to,
        "text": message.content,
        "username": message.author.nick,
        "icon_url": message.author.display_avatar.url,
        "file_ids": file_ids
    }
    response = requests.post(webhook_url, json=payload)
    print(response.content)"""

    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})