#!/usr/bin/env python
"""This is the discord bot for ESXR"""
import re
import os
import logging
import discord
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())
CLIENT = discord.Client()
LOGGER = logging.getLogger('discord')
logging.basicConfig(level=logging.INFO)
HANDLER = logging.FileHandler(
    filename='discord.log', encoding='utf-8', mode='w')
HANDLER.setFormatter(logging.Formatter(
    '%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
LOGGER.addHandler(HANDLER)


def is_me(message):
    """Check if user is self"""
    return message.author == CLIENT.user


@CLIENT.event
async def on_ready():
    """On ready function for the bot"""
    print('Logged in as ' + CLIENT.user.name)
    print('Ready to use.')


@CLIENT.event
async def on_message(message):
    """Handle messages on guild"""
    if re.match(r"^!(\w+)", message.content.split(" ")[0]):
        args = message.content.split(" ")
        del args[0]
        print(args)
        if message.content.startswith('!botclear'):
            deleted = await CLIENT.purge_from(message.channel, limit=100, check=is_me)
            await CLIENT.send_message(message.channel,
                                      '{} message(s) supprimé(s)'.format(len(deleted)))
        elif message.content.startswith('!clearusermessage'):
            try:
                num = args[0]
                user = args[1]
                counter = 0
                tmp = await CLIENT.send_message(
                    message.channel,
                    'Deleting {} message(s) of {}'
                    .format(num, user))
                async for message in CLIENT.logs_from(message.channel, limit=int(num)):
                    dir(message)
                    if message.author == user:
                        await CLIENT.delete_message(message)
                        counter += 1
                await CLIENT.edit_message(
                    tmp,
                    'Deleted {} message(s) of {}'
                    .format(counter, user))
            except IndexError:
                await CLIENT.send_message(message.channel,
                                          'Merci de donner un nombre de message et un utilisateur.')
                await CLIENT.send_message(message.channel,
                                          '`!clearusermessage 50 @username`')
        else:
            await CLIENT.send_message(message.channel, 'Commande inconnue')
CLIENT.run(os.environ.get("DISCORD_TOKEN"))
