import logging

import disnake
from disnake import Option, OptionType
from disnake.ext import commands

import lib


class General(commands.Cog):
    def __init__(self, bot):
        self.bot = bot  # defining bot as global var in class

    @commands.Cog.listener()  # this is a decorator for events/listeners
    async def on_ready(self):
        for g in self.bot.get_all_members():
            lib.DB.prepare_db(g.guild.id)
        for g in self.bot.get_all_members():
            lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, g.guild.id)

        logging.info(f'Cog {__name__.split(".")[1]} is ready!.')

    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        for g in guild.members:
            lib.DB.fill_bd(g.name, g.id, g.bot, g.nick, guild.id)

    @commands.Cog.listener()
    async def on_member_join(self, member):
        lib.DB.fill_bd(member.name, member.id, member.bot, member.nick, member.guild.id)

        bot_role = lib.Commands.read_json(member.guild.id, 'bot_role')  # Get bot role
        guest_role = lib.Commands.read_json(member.guild.id, 'guest_role')  # Get guest role

        if bot_role and guest_role:
            if member.bot == 0:
                role = disnake.utils.get(member.guild.roles, id=guest_role)
            else:
                role = disnake.utils.get(member.guild.roles, id=bot_role)
            logging.info(f"Adding to {member} role {role}")
            await member.add_roles(role)

    @commands.Cog.listener()
    async def on_member_update(self, before: disnake.Member, after: disnake.Member):
        sql_update_query = f"""UPDATE "{after.guild.id}" set nick = ? where userid = ?"""
        data_tuple = (after.nick, before.id)
        lib.DB.work_with_db(sql_update_query, data_tuple)

    @commands.slash_command(
        name="info",
        description="Read list of tracks for user",
        options=[
            Option("user", "Specify any user", OptionType.user),
        ]
    )
    async def info(self, inter, user=None):
        user = user or inter.author
        audio = lib.DB.read_db(inter.guild.id, user.id)
        rolelist = [r.mention for r in user.roles if r != inter.guild.default_role]
        if rolelist:
            roles = "\n".join(rolelist)
        else:
            roles = "Not added any role"

        if audio is None:
            audios = "Not selected audio"
        else:
            audios = "• " + "\n• ".join(sorted(audio.split(", ")))

        emb = disnake.Embed(
            title=f"General information",
            description=f"General information on server about {user}"
        )
        emb.set_thumbnail(url=user.avatar.url)
        emb.add_field(name="General info",
                      value=f"Username: {user}\n"
                            f"Nickname: {user.nick}\n"
                            f"Joined at: {user.joined_at.strftime('%A, %B %d %Y @ %H:%M:%S')}", inline=False)
        emb.add_field(name="Audio list", value=f"{audios}", inline=True)
        emb.add_field(name="Roles list", value=f"{roles}", inline=True)
        emb.set_footer(text="Information requested by: {}".format(inter.author.display_name))

        await inter.response.send_message(embed=emb, ephemeral=True)

    @commands.slash_command(
        name="set_guest_role",
        description="Set Default bot role",
        options=[
            Option("role", "Specify role", OptionType.role, required=True),
        ]
    )
    @commands.has_permissions(administrator=True)
    async def set_guest_role(self, ctx, role):
        await lib.Commands.write_json(ctx.guild.id, "guest_role", role.id)
        await ctx.send(f"Setted up dsss bot role to: `{role.name}`", ephemeral=True)

    @commands.command(name="set_prefix")
    @commands.has_permissions(administrator=True)
    async def command_set_prefix(self, ctx, prefix: str):
        await lib.Commands.set_prefix(ctx, prefix)
        await ctx.reply(f"Prefix set to: `{prefix}`")

    @commands.slash_command(
        name="set_prefix",
        description="Setting up bot prefix",
        options=[
            Option("prefix", "Specify prefix", OptionType.string, required=True),
        ]
    )
    @commands.has_permissions(administrator=True)
    async def slash_set_prefix(self, inter, prefix: str):
        await lib.Commands.set_prefix(inter, prefix)
        await inter.responce.send_message(f"Prefix set to: `{prefix}`", ephemeral=True)

    @slash_set_prefix.error
    async def set_prefix_error(self, inter, prefix):
        await inter.response.send_message('You don`t have permissions', ephemeral=True)

    @commands.slash_command(
        name="set_trigger_role",
        description="Setting up role to trigger bot",
        options=[
            Option("role", "Specify role", OptionType.role, required=True),
        ]
    )
    @commands.has_permissions(administrator=True)
    async def set_trigger_role(self, inter, role):
        await lib.Commands.write_json(inter.guild.id, "tigger_role", role.id)
        await inter.responce.send(f"Role to trigger set to : `{role.name}`", ephemeral=True)

    @commands.slash_command(
        name="set_bot_role",
        description="Set Default bot role",
        options=[
            Option("role", "Specify role", OptionType.role, required=True),
        ]
    )
    @commands.has_permissions(administrator=True)
    async def set_bot_role(self, ctx, role):
        await lib.Commands.write_json(ctx.guild.id, "bot_role", role.id)
        await ctx.send(f"Setted up bot role to: `{role.name}`", ephemeral=True)

    @commands.slash_command()
    async def help(self, inter):
        embed = disnake.Embed(
            title='Help', description='', colour=disnake.Colour.blue())
        embed.set_footer(text='Have fun!')

        embed.add_field(
            name='Prefix',
            value=
            f'The current prefix for this server is {self.bot.command_prefix}',
            inline=True)

        await inter.response.send_message(embed=embed)


def setup(bot):  # an extension must have a setup function
    bot.add_cog(General(bot))  # adding a cog
