"""Start the Discord bot and connect to Discord."""
import asyncio
import importlib
import logging

from django.conf import settings
from django.core.management.base import BaseCommand

from bot import hitomi
from bot.api import hitomi_api

logger = logging.getLogger(__name__)


@hitomi.event
async def on_ready():
    """Print some basic login info to the console, when the bot connects."""
    logger.info("Logged in as {0:s} ({1:s})".format(hitomi.user.name, hitomi.user.id))

    # now load bot plugins
    for plugin in settings.BOT_PLUGINS:
        importlib.import_module(plugin)


@hitomi.event
async def on_message(message):
    """Call all registered on_message handlers."""
    for handler in hitomi.on_message_handlers:
        handler(message)

    # let other stuff happen
    await hitomi.process_commands(message)


async def run_bot():
    """Initialize and begin the bot in an asyncio context."""
    await hitomi.login(settings.DISCORD_BOT_TOKEN)
    await hitomi.connect()


class Command(BaseCommand):
    help = "Start the Discord bot and connect to Discord."

    def handle(self, *args, **options):
        loop = asyncio.get_event_loop()
        handler = hitomi_api.make_handler()
        api_server = loop.create_server(handler, '0.0.0.0', 8080)
        futures = asyncio.gather(run_bot(), api_server)
        try:
            loop.run_until_complete(futures)
        except:
            loop.run_until_complete(hitomi.logout())
        finally:
            loop.close()