import discord
import asyncio
import configparser
from nsfw_bot import NSFWBot
from youtube_bot import YoutubeBot

client = discord.Client()
config = configparser.RawConfigParser()
config.read('config.cfg')
youtube = YoutubeBot(client, config)


@client.async_event
def on_ready():
    print("Serveur demarré et opérationnel. Que le dessert vous accompagne.")


@client.async_event
def on_message(message: discord.Message):
    if message.content.startswith('!r34 ') and config.getboolean("NSFWBot", "enabled"):
        try:
            yield from client.send_message(message.channel, NSFWBot.search_r34(message))
        except ValueError as ve:
            print("Erreur NSFWBot : " + str(ve))

    if message.content.startswith('!play'):
        try:
            if len(message.content.split()) > 1:
                yield from youtube.play(message.content.split(maxsplit=1)[1])
            else:
                yield from youtube.play()
        except Exception as ex:
            print("Erreur Youtube bot : " + str(ex))

    if message.content.startswith('!pause'):
        try:
            yield from youtube.pause()
        except Exception as ex:
            print("Erreur Youtube bot : " + str(ex))

    print("Dessert : " + message.content)


@asyncio.coroutine
def bot_dessert():
    yield from client.login(config.get("Login", "mail"), config.get("Login", "password"))
    yield from client.connect()


loop = asyncio.get_event_loop()

try:
    loop.run_until_complete(bot_dessert())
    print("Oui")
except Exception as e:
    loop.run_until_complete(client.logout())
    print("Non" + str(e))
finally:
    loop.close()
