from discord.ext import commands
import discord
import time
import psutil
import injector
import cogs.utils.embeds as embeds
import database

# Gives us a rough estimate of when the bot started
start_time = time.time()


class Stats:
    """Bot stats"""

    def __init__(self, bot):
        self.bot = bot
        self.command_prefix = injector.get_options()['settings']['command_prefix'][0]

    @staticmethod
    def seconds_to_d_h_m_s(time):
        day = time // (24 * 3600)
        time = time % (24 * 3600)
        hour = time // 3600
        time %= 3600
        minutes = time // 60
        time %= 60
        seconds = time
        return "{0} days, {1} hours, {2} minutes and {3} seconds".format(day, hour, minutes, seconds)

    @commands.command()
    async def up_time(self, ctx):
        """Returns the bot up time"""
        await ctx.send(embed=embeds.info_message("Up time", "Current process up time: {0}".format(
                 self.seconds_to_d_h_m_s(round(time.time() - start_time)))))

    @commands.command()
    async def system_stats(self, ctx):
        """Return info about the current system"""
        cpu_percent = psutil.cpu_percent(interval=1, percpu=False)
        if cpu_percent <= 50:
            colour = injector.get_green_palette()[500]
        elif cpu_percent <= 75:
            colour = injector.get_orange_palette()[500]
        else:
            colour = injector.get_red_palette()[500]

        e = discord.Embed(title="System Stats", colour=colour)
        e.add_field(name="CPU USAGE", value="{0}%".format(cpu_percent))
        e.add_field(name="MEMORY USAGE", value="{0}%".format(psutil.swap_memory().percent))
        e.add_field(name="DISK USAGE", value="{0}%".format(psutil.disk_usage('/').percent))
        await ctx.send(embed=e)

    @commands.command()
    async def command_usage(self, ctx, name: str):
        """Returns the number of times a command has been used on the current server"""
        result = await database.Command().find(name=name, guild_id=ctx.guild.id)
        if result is None:
            await ctx.send(embed=embeds.error_message("Command not used or invalid"))
        else:
            await ctx.send(embed=embeds.info_message("Command {0} has been used {1} times".format(name, result['uses']),
                                                     "Maybe you should run it? `{0}{1}`".format(self.command_prefix,
                                                                                                name)))

    @commands.command()
    async def most_used_command(self, ctx):
        result = await database.Command().top('uses', guild_id=ctx.guild.id)
        if result is None:
            await ctx.send(embed=embeds.error_message("No commands found"))
        else:
            await ctx.send(embed=embeds.info_message("{0} is the most used commands. It has been used {1} times".format(
                result['name'], result['uses']), "Maybe you should run it? `{0}{1}`".format(self.command_prefix,
                                                                                            result['name'])))


def setup(bot):
    bot.add_cog(Stats(bot))
