from discord.ext import commands
import logging
import modules.perms as perms
import asyncio

logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='logs/suda.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

modules = ["music", 'help_suda']
bot = commands.Bot(command_prefix="!")


'''@bot.event
async def on_command_error(ctx, error):
    channel = ctx.message.channel
    err = ("```" + str(error) + "```")
    pages = bot.formatter.format_help_for(ctx, ctx.command)
    if isinstance(error, commands.errors.MissingRequiredArgument):
        for page in pages:
            await ctx.send(channel, err + page)
        return
    elif isinstance(error, commands.errors.BadArgument):
        for page in pages:
            await ctx.send(channel, err + page)
        return
    elif isinstance(error, commands.errors.CommandNotFound):
        return
    else:
        print(error)
        return'''


@bot.event
async def on_ready():
    print(bot.user.name + ' has successfully launched')
    print(bot.user.id)
    print('--------------------')


@bot.command()
async def test(ctx):
    await ctx.send('Cephalon Suda is Online')


@bot.command(pass_context=True)
@perms.admin_or_permissions(administrator=True)
async def reload_suda(ctx, selmodule=None):
    """Reloads all or specified module"""
    await ctx.trigger_typing()
    await asyncio.sleep(1)
    if selmodule is None:
        for y in modules:
            try:
                z = 'modules.' + y
                bot.unload_extension(z)
                bot.load_extension(z)
            except Exception:
                await ctx.send("Failed to load module '" + y + "'. Reloading has stopped.")
                return
        await ctx.send('Reloaded all modules for Cephalon Suda')
    else:
        try:
            z = 'modules.' + selmodule
            bot.unload_extension(z)
            bot.load_extension(z)
            await ctx.send("Reloaded module '" + selmodule + "' for Cephalon Suda")
        except ModuleNotFoundError:
            await ctx.send("'" + selmodule + "' is not a valid module")
        except Exception:
            await ctx.send("Failed to load module '" + selmodule + "'")


@bot.command()
async def quit_suda():
    await bot.logout()


if __name__ == "__main__":
    for x in modules:
        module = 'modules.' + x
        try:
            bot.load_extension(module)
        except Exception as e:
            exc = '{}: {}'.format(type(e).__name__, e)
            print('Failed to load extension {}\n{}'.format(x, exc))

    bot.run("MzA1MjA1MzYzNTUxMTA5MTIy.C93DJg.XNk3jT-Jg65VDShK2kDrfwFloqw")
