# Path: dozer/cogs/actionlogs.py
# class CustomJoinLeaveMessages(db.DatabaseTable):
#     """Holds custom join leave messages"""
#     __tablename__ = 'memberlogconfig'
#     __uniques__ = 'guild_id'
# 
#     @classmethod
#     async def initial_create(cls):
#         """Create the table in the database"""
#         async with db.Pool.acquire() as conn:
#             await conn.execute(f"""
#             CREATE TABLE {cls.__tablename__} (
#             guild_id bigint PRIMARY KEY NOT NULL,	            
#             memberlog_channel bigint NOT NULL,	   
#             name varchar NOT NULL
#             )""")
# 
#     def __init__(self, guild_id, channel_id=None, ping=None, join_message=None, leave_message=None):
#         super().__init__()
#         self.guild_id = guild_id
#         self.channel_id = channel_id
#         self.ping = ping
#         self.join_message = join_message
#         self.leave_message = leave_message
# 
#     @classmethod
#     async def get_by(cls, **kwargs):
#         results = await super().get_by(**kwargs)
#         result_list = []
#         for result in results:
#             obj = CustomJoinLeaveMessages(guild_id=result.get("guild_id"), channel_id=result.get("channel_id"),
#                                           ping=result.get("ping"),
#                                           join_message=result.get("join_message"),
#                                           leave_message=result.get("leave_message"))
#             result_list.append(obj)
#         return result_list
# 
#     async def version_1(self):
#         """DB migration v1"""
#         async with db.Pool.acquire() as conn:
#             await conn.execute(f"""
#             alter table memberlogconfig rename column memberlog_channel to channel_id;
#             alter table memberlogconfig alter column channel_id drop not null;
#             alter table {self.__tablename__} drop column IF EXISTS name;
#             alter table {self.__tablename__}
#                 add IF NOT EXISTS ping boolean default False;
#             alter table {self.__tablename__}
#                 add IF NOT EXISTS join_message text default null;
#             alter table {self.__tablename__}
#                 add IF NOT EXISTS leave_message text default null;
#             """)
# 
#     __versions__ = [version_1]
# 
# Path: dozer/bot.py
# DOZER_LOGGER = logging.getLogger('dozer')


import asyncio
import time
import typing
import discord
import discord.utils
from discord.ext.commands import cooldown, BucketType, has_permissions, BadArgument, guild_only
from discord_slash import cog_ext, SlashContext
from ._utils import *
from .actionlogs import CustomJoinLeaveMessages
from .. import db
from ..bot import DOZER_LOGGER
from ..db import *
        await RoleMenu.delete(message_id=message_id)

    @Cog.listener()
    async def on_raw_reaction_add(self, payload):
        """Raw API event for reaction add, passes event to action handler"""
        await self.on_raw_reaction_action(payload)

    @Cog.listener()
    async def on_raw_reaction_remove(self, payload):
        """Raw API event for reaction remove, passes event to action handler"""
        await self.on_raw_reaction_action(payload)

    async def on_raw_reaction_action(self, payload):
        """Called whenever a reaction is added or removed"""
        message_id = payload.message_id
        reaction = str(payload.emoji)
        reaction_roles = await ReactionRole.get_by(message_id=message_id, reaction=reaction)
        if len(reaction_roles):
            guild = self.bot.get_guild(payload.guild_id)
            member = guild.get_member(payload.user_id)
            role = guild.get_role(reaction_roles[0].role_id)
            if member.bot:
                return
            if role:
                try:
                    if payload.event_type == "REACTION_ADD":
                        await member.add_roles(role, reason="Automatic Reaction Role")
                    elif payload.event_type == "REACTION_REMOVE":
                        await member.remove_roles(role, reason="Automatic Reaction Role")
                except discord.Forbidden:

# Path: dozer/cogs/actionlogs.py
# class CustomJoinLeaveMessages(db.DatabaseTable):
#     """Holds custom join leave messages"""
#     __tablename__ = 'memberlogconfig'
#     __uniques__ = 'guild_id'
# 
#     @classmethod
#     async def initial_create(cls):
#         """Create the table in the database"""
#         async with db.Pool.acquire() as conn:
#             await conn.execute(f"""
#             CREATE TABLE {cls.__tablename__} (
#             guild_id bigint PRIMARY KEY NOT NULL,	            
#             memberlog_channel bigint NOT NULL,	   
#             name varchar NOT NULL
#             )""")
# 
#     def __init__(self, guild_id, channel_id=None, ping=None, join_message=None, leave_message=None):
#         super().__init__()
#         self.guild_id = guild_id
#         self.channel_id = channel_id
#         self.ping = ping
#         self.join_message = join_message
#         self.leave_message = leave_message
# 
#     @classmethod
#     async def get_by(cls, **kwargs):
#         results = await super().get_by(**kwargs)
#         result_list = []
#         for result in results:
#             obj = CustomJoinLeaveMessages(guild_id=result.get("guild_id"), channel_id=result.get("channel_id"),
#                                           ping=result.get("ping"),
#                                           join_message=result.get("join_message"),
#                                           leave_message=result.get("leave_message"))
#             result_list.append(obj)
#         return result_list
# 
#     async def version_1(self):
#         """DB migration v1"""
#         async with db.Pool.acquire() as conn:
#             await conn.execute(f"""
#             alter table memberlogconfig rename column memberlog_channel to channel_id;
#             alter table memberlogconfig alter column channel_id drop not null;
#             alter table {self.__tablename__} drop column IF EXISTS name;
#             alter table {self.__tablename__}
#                 add IF NOT EXISTS ping boolean default False;
#             alter table {self.__tablename__}
#                 add IF NOT EXISTS join_message text default null;
#             alter table {self.__tablename__}
#                 add IF NOT EXISTS leave_message text default null;
#             """)
# 
#     __versions__ = [version_1]
# 
# Path: dozer/bot.py
# DOZER_LOGGER = logging.getLogger('dozer')


# Path: dozer/cogs/roles.py
import asyncio
import time
import typing
import discord
import discord.utils
from discord.ext.commands import cooldown, BucketType, has_permissions, BadArgument, guild_only
from discord_slash import cog_ext, SlashContext
from ._utils import *
from .actionlogs import CustomJoinLeaveMessages
from .. import db
from ..bot import DOZER_LOGGER
from ..db import *

        await RoleMenu.delete(message_id=message_id)

    @Cog.listener()
    async def on_raw_reaction_add(self, payload):
        """Raw API event for reaction add, passes event to action handler"""
        await self.on_raw_reaction_action(payload)

    @Cog.listener()
    async def on_raw_reaction_remove(self, payload):
        """Raw API event for reaction remove, passes event to action handler"""
        await self.on_raw_reaction_action(payload)

    async def on_raw_reaction_action(self, payload):
        """Called whenever a reaction is added or removed"""
        message_id = payload.message_id
        reaction = str(payload.emoji)
        reaction_roles = await ReactionRole.get_by(message_id=message_id, reaction=reaction)
        if len(reaction_roles):
            guild = self.bot.get_guild(payload.guild_id)
            member = guild.get_member(payload.user_id)
            role = guild.get_role(reaction_roles[0].role_id)
            if member.bot:
                return
            if role:
                try:
                    if payload.event_type == "REACTION_ADD":
                        await member.add_roles(role, reason="Automatic Reaction Role")
                    elif payload.event_type == "REACTION_REMOVE":
                        await member.remove_roles(role, reason="Automatic Reaction Role")
                except discord.Forbidden:

                    DOZER_LOGGER.debug(f"Unable to add reaction role in guild {guild} due to missing permissions")