"""
Generic tag bot, yay.
"""
import asyncio
import copy
import shlex
import traceback

import discord
from discord.ext import commands
from discord.ext.commands import CommandError, CommandInvokeError, CommandNotFound

from joku.cogs._common import Cog
from joku.core.bot import Context, Jokusoramame
from joku.core.tagengine import TagEngine


class Tags(Cog):
    def __init__(self, bot: Jokusoramame):
        super().__init__(bot)

        self.engine = TagEngine(self.bot)

    def _sanitize_name(self, name: str) -> str:
        return name.replace("@everyone", "@\u200beveryone").replace("@here", "@\u200bhere")

    @commands.group(pass_context=True, invoke_without_command=True,
                    aliases=["tags"])
    async def tag(self, ctx: Context, *, name: str):
        """
        Tags are like aliases or autoresponses that can be added to the bot.

        They are made with `tag create`, and deleted with `tag delete`.
        To be accessed, they are simply called like commands are.
        """
        tag, alias = await ctx.bot.database.get_tag(ctx.message.guild, name, return_alias=True)
        if not tag:
            await ctx.channel.send(":x: Tag not found.")
            return

        if alias is not None:
            em = discord.Embed(title=alias.alias_name, description="Alias for `{}`".format(tag.name))
            owner = ctx.bot.get_member(alias.user_id)
        else:
            em = discord.Embed(title=tag.name, description="```{}```".format(tag.content))
            owner = ctx.bot.get_member(tag.user_id)

        em.add_field(name="Owner", value=owner.mention if owner else "<Unknown>")
        em.add_field(name="Last Modified", value=tag.last_modified.isoformat())

        # Display the tag info.
        await ctx.channel.send(embed=em)

    @tag.command()
    async def copy(self, ctx: Context, guild_id: int, *, tag_name: str):
        """
        Copies a tag from another guild.
        
        This requires the guild ID of the guild to copy.
        To get this, enable Developer Mode and Copy ID.
        """
        guild = self.bot.get_guild(guild_id)