import re
import discord
from discord.ext import commands
import random
from BotResources import PDB_KNOWN_BOT_IDS, check_and_reply_to_ping

regex_link = re.compile('(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)')


### Langvars for the response strings
### {%<langvar>%}
### Possible langvars
### 'mtn_user' - Mentions the user that sent the original message - {%mtn_user%}
### 'ref_og_channel' - Reference the channel that the user sent the original message - {%ref_og_channel%}
### 'ref_first_link' - Reference the first link that the user originally sent - {%ref_first_link%}
### 'ref_og_msg' - Reference the original message that the user sent - {%ref_og_msg%}

random_message = ["{%mtn_user%}, tsk tsk. Links belong here:\n{%ref_og_msg%}", "{%mtn_user%}, the channel is quite literally called 'links':\n{%ref_og_msg%}",
                  "{%mtn_user%}. Well, well, well, if it isn't the man who's been posting links in the wrong channel.\n'{%ref_og_msg%}'",
                  "{%mtn_user%}, isn't this convenient. A whole channel for links and you put links in, and you put {%ref_first_link_%} in {%ref_og_channel%}.\n\n'{%ref_og_msg%}'",
                  ]

### Channel IDs
# testing 918029426397184000
# links 767303243285790721
# welcome 757379843792044102
# the-round-table 367396189529833474

class LinkCop(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reply_channel_id = 767303243285790721

        self.blocked_channels = [
            757379843792044102,
            367396189529833474
        ]

        self.whitelisted_groups = [
            757375638926655709, # Superadmins
            758792783020163084 # Bots
        ]

        # Bring in the known bot IDs from PDB bots
        self.whitelisted_ID = PDB_KNOWN_BOT_IDS

        self.whitelisted_ID['Carl Bot'] = 235148962103951360

        self.add_events()

    def add_events(self):
        @self.bot.event
        async def on_message(ctx):
            if self.bot.user.id not in self.whitelisted_ID:
                self.whitelisted_ID.append(self.bot.user.id)

            if ctx.channel.id in self.blocked_channels:
                if ctx.author.id not in self.whitelisted_ID:
                    try:
                        if not any(item.id in self.whitelisted_groups for item in ctx.author.roles):
                            if check_message(ctx.content):
                                print('Msg with links detected in a blocked channel')

                                response_text = self.generate_response(ctx)

                                # Send the response in the links channel
                                await self.send_message(response_text)
                                # Delete the original message
                                await ctx.delete()
                    except AttributeError as err:
                        print(f"Link Cop Error: '{err}'")
                        print(f"Bot or other non-user that has not been whitelisted sent a message")

            await check_and_reply_to_ping(self.bot, ctx)

    async def send_message(self, message):
        send_channel = self.bot.get_channel(id=self.reply_channel_id)
        await send_channel.send(message)

    def generate_response(self, ctx):
        # Get message
        og_message_text = ctx.content

        # Get the random string to edit
        response_text = random_message[random.randint(0, len(random_message)-1)]

        # Get the sender of the message
        member = ctx.author.id
        mtn_member = f"<@{member}>"

        # Get the name of the channel the message was sent
        ref_og_channel = ctx.channel.name

        # Get the first link the user sent
        ref_first_link = get_links(message_text=og_message_text)
        if ref_first_link:
            ref_first_link = ref_first_link[0]

        # Mention the user
        response_text = str(response_text).replace("{%mtn_user%}", mtn_member)

        # Reference the original channel
        response_text = str(response_text).replace("{%ref_og_channel%}", ref_og_channel)

        # Reference the original message
        response_text = str(response_text).replace("{%ref_og_msg%}", og_message_text)

        # Reference the first link
        response_text = str(response_text).replace("{%ref_first_link%}", ref_first_link)

        return response_text


def check_message(message_text):
    matches = regex_link.findall(message_text)

    if bool(matches):
        return True
    else:
        return False


def get_links(message_text):
    links = regex_link.findall(message_text)

    print(links)

    if len(links) > 0:
        return links


def setup(bot: commands.Bot):
    bot.add_cog(LinkCop(bot))
