# -*- coding: utf-8 -*-

"""
MIT License

Copyright (c) 2017 - 2018 FrostLuma

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import discord

from mousey import Cog, commands


class Group:
    """Represents a self assignable role in a Discord Guild."""

    __slots__ = ('role', 'description')

    def __init__(self, role, description):
        self.role = role
        self.description = description

    @classmethod
    async def convert(cls, ctx, argument):
        _roles = sorted(ctx.guild.roles, key=lambda x: len(x.name))
        role = discord.utils.find(lambda x: argument.lower() in x.name.lower(), _roles)

        if role is None:
            raise commands.BadArgument(
                f'Group "{argument}" not found! See "{ctx.prefix}groups" for a list of available groups.'
            )

        async with ctx.bot.db.acquire() as conn:
            description = await conn.fetchval('SELECT description FROM groups WHERE role_id = $1', role.id)

        if description is None:
            raise commands.BadArgument(
                f'Group "{argument}" not found! See "{ctx.prefix}groups" for a list of available groups.'
            )

        return cls(role, description)

    @staticmethod
    async def all(pool, guild):
        """
        Fetch all groups for a Guild.

        Parameters
        ----------
        pool : asyncpg.pool.Pool
            The database connection pool to fetch groups with.
        guild : discord.Guild
            The Guild to fetch groups for.

        Returns
        -------
        List[Group]
            The groups available in the given Guild.
        """

        async with pool.acquire() as conn:
            records = await conn.fetch(
                """
                SELECT groups.role_id, groups.description
                FROM groups JOIN roles ON groups.role_id = roles.role_id
                WHERE roles.guild_id = $1
                """,
                guild.id
            )

        groups = []

        for record in records:
            role = discord.utils.get(guild.roles, id=record['role_id'])
            groups.append(Group(role, record['description']))

        return sorted(groups, key=lambda x: x.role.name.lower())


class Groups(Cog, depends=['Config']):
    """Self assignable roles."""

    @commands.group(aliases=['group'])
    @commands.bot_has_permissions(embed_links=True)
    async def groups(self, ctx):
        """Shows all available groups."""

        descriptions = []
        groups = await Group.all(self.db, ctx.guild)

        for group in groups:
            descriptions.append(f'**{group.role}** - {group.description if group.description else "no description"}')

        description = '\n'.join(descriptions)
        embed = discord.Embed(title=f'{ctx.guild} Group list', color=ctx.color, description=description)

        _prefix = ctx.prefix if ctx.prefix != f'{ctx.me.mention} ' else f'@{self.mousey.user} '
        embed.set_footer(text=f'To join or leave any group use {_prefix}join <group> and {_prefix}leave <group>.')

        await ctx.send(embed=embed)

    @commands.command()
    @commands.bot_has_permissions(manage_roles=True)
    async def join(self, ctx, *, group: Group):
        """Join a group."""

        await self._assign_command(ctx, group, 'joined')

    @commands.command()
    @commands.bot_has_permissions(manage_roles=True)
    async def leave(self, ctx, *, group: Group):
        """Leave a group."""

        await self._assign_command(ctx, group, 'left')

    async def _assign_command(self, ctx, group, verb):
        """
        Handles group joining and leaving.

        Parameters
        ----------
        ctx : commands.Context
            The context to the command being executed.
        group : Group
            The group to assign or remove.
        verb : str
            Whether the role should be assigned or removed.
        """

        action = 'add_roles' if verb == 'joined' else 'remove_roles'

        try:
            method = getattr(ctx.author, action)
            await method(group.role, reason=f'{ctx.author} {ctx.author.id} {verb} this group role.')
        except discord.HTTPException:
            return await ctx.send(f'I can\'t assign this role due to it being too high in the hierarchy.')

        await ctx.send(f'You\'ve {verb} `{group.role}`!')

    @groups.command()
    @commands.user_has_permissions(manage_roles=True)
    async def create(self, ctx, role: discord.Role, *, description: str=''):
        """Create a new group or update a description."""

        async with self.db.acquire() as conn:
            await conn.execute(
                """
                INSERT INTO groups (role_id, description) VALUES ($1, $2)
                ON CONFLICT (role_id) DO UPDATE SET description = $2
                """,
                role.id,
                description,
            )

        await ctx.send(f'Successfully created group `{role}` with description `{description}`')

    @groups.command()
    @commands.user_has_permissions(manage_roles=True)
    async def delete(self, ctx, *, group: Group):
        """Delete a group."""

        async with self.db.acquire() as conn:
            await conn.execute('DELETE FROM groups WHERE role_id = $1', group.role.id)

        await ctx.send(f'Successfully deleted group `{group.role}`')


def setup(mousey):
    mousey.add_cog(Groups(mousey))
