import asyncio
import aiocron
from async_timeout import timeout

import yaml
from yaml.loader import SafeLoader

import discord
import discord.utils
from discord import option
from discord.ext import commands

import mysql.connector
from mysql.connector import Error

import time
from datetime import date, datetime, tzinfo

import os

import flask

from easy_pil import Canvas, Editor, Font, Text, font, load_image_async
from PIL import Image, ImageDraw, ImageFont, ImageOps
import pytz
import socket

from cogs.encrypting import encode, decode, encrypt, decrypt
from cogs.database import select_database, insert_database, update_database

timezone = pytz.timezone("Europe/Berlin")

zeit = datetime.now()

time_date = zeit.strftime("%Y/%m/%d")
time_year = zeit.strftime("%Y")
time_month = zeit.strftime("%m")
time_day = zeit.strftime("%d")

time_time = zeit.strftime("%H:%M:%S")
time_hour = zeit.strftime("%H")
time_minute = zeit.strftime("%M")
time_second = zeit.strftime("%S")

time_datetime = zeit.strftime("%Y/%m/%d" "%H:%M:%S")

client = None

## Class

class Stats(commands.Cog):
    
    def __init__(self, bot):
        self.bot = bot
        global path
        path = bot.path
        global client
        client = self.bot


    @aiocron.crontab('*/4 * * * *', start=True, tz=timezone)
    @commands.Cog.listener()
    async def severstats():
        with open(fr'{path}/Configs/server.yaml', encoding='utf8') as f:
            data = yaml.load(f, Loader=SafeLoader)
            length = len(data["Config.Server"])

        servers = []
        try:
            for i in range(0, length, 1):
                servers.append([data["Config.Server"][i]["name"], data["Config.Server"][i]["guild"]])
        except StopIteration:
            return
            
        for server in servers:
            with open(fr'{path}/Configs/{server[0]}/stats.yaml', encoding='utf8') as f:
                data = yaml.load(f, Loader=SafeLoader)
                guild = client.get_guild(int(server[1]))


            for stat in data["Config.Stats"]:
                try:
                    channelname = data["Config.Stats"][stat]["channelname"]
                    channel = guild.get_channel(int(data["Config.Stats"][stat]["channelid"]))
                    roles = data["Config.Stats"][stat]["roles"]
                    count = 0


                    for items in roles:
                        for item in items["roleid"]:
                            memberstat = None
                            if item == "all":
                                memberstat = True
                            else:
                                role = guild.get_role(int(item))

                            for member in guild.members:
                                if memberstat == True:
                                    count += 1
                        
                                else:
                                    try:
                                        if role in member.roles and str(member.status) in items["status"]:
                                            count += 1
                                            pass
                                    except Exception:
                                        pass
                except AttributeError:
                    pass

                try:
                    await channel.edit(name=f'{channelname.replace("X", f"{count}")}')
                except AttributeError:
                    pass



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