import asyncio
from dis import disco
import sys
import discord
from discord.ext import commands, tasks
import logging
import pprint
import pytomlpp
from quart import Quart, request

config = pytomlpp.load(open("config.toml", "r"))

class Krentebot(commands.Bot):
    # def __init__(self, *args, **kwargs):
    #     super(Krentebot, self).__init__(*args, **kwargs)

    #     loop = asyncio.get_event_loop()

    #     self.an_chan = loop.run_until_complete(self.fetch_channel(995494690063384637))

    async def on_ready(self):
        self.log = logging.getLogger("Krentebot")
        self.log.setLevel(logging.DEBUG)
        file_handler = logging.FileHandler(filename='krentebot.log', encoding='utf-8', mode='w')
        file_handler.setFormatter(logging.Formatter('[%(asctime)s:%(levelname)s:%(name)s] %(message)s'))
        stdout_handler = logging.StreamHandler(stream=sys.stdout)
        stdout_handler.setFormatter(logging.Formatter('[%(asctime)s:%(levelname)s:%(name)s] %(message)s'))
        self.log.addHandler(file_handler)
        self.log.addHandler(stdout_handler)

        self.log.info('Logged on as {0}!'.format(self.user))

        self.an_chan = await self.fetch_channel(995494690063384637)

        await bot.change_presence(status=discord.Status.online, activity=discord.Game(name="パーティーをする"))

    # async def on_message(self, message):
    #     print('Message from {0.author}: {0.content}'.format(message))


bot = Krentebot(command_prefix="!")
web = Quart(__name__)


# ====== GLOBAL =======



# ====== BOT =======



@bot.command(name="sac")
async def set_announcement_channel(ctx):
    await ctx.channel.send("Channel set succesfully!")
    bot.an_chan = ctx.channel


# ====== WEB =======
@web.route("/")
async def home():
    return("test")

@web.route("/api/send_announcement", methods=["GET", "POST"])
async def send_announcement():
    # rem_ip = request.remote_addr
    # data = await request.get_json()
    await bot.an_chan.send("Test announcement from webhook!")
    return "Announcement sent!"

if __name__ == "__main__":
    bot.loop.create_task(web.run_task(config['web']['host'], config['web']['port']))

    bot.run(config['bot']['token'])