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

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")




## Class

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

    @commands.slash_command(name="welcome", description="Senden der Willkommens-Nachricht")
    async def welcome(
        self, ctx: discord.ApplicationContext, member : discord.Member):

        with open(fr'{path}/Configs/server.yaml', encoding='utf8') as f:
            data = yaml.load(f, Loader=SafeLoader)
            try:
                servername = next(item["name"] for item in data["Config.Server"] if str(ctx.guild.id) == str(item["guild"]))
                checkback = await check_status(servername, self.bot)
            except StopIteration:
                await ctx.respond("Error in Syntax", ephemeral=True)
                return
            try:
                backsend = await globals()[f"send_{checkback.lower()}"](servername, member, self.bot)
            except Exception:
                backsend = None

            await ctx.respond(backsend, ephemeral=True)
            return


    @commands.Cog.listener()
    async def on_member_join(self, member):
        with open(fr'{path}/Configs/server.yaml', encoding='utf8') as f:
            data = yaml.load(f, Loader=SafeLoader)
            length = len(data["Config.Server"])

            try:
                for i in range(0, length, 1):
                    if str(member.guild.id) == str(data["Config.Server"][i]["guild"]):
                        servername = data["Config.Server"][i]["name"]
                        checkback = await check_status(servername, self.bot)

            except Exception:
                await globals()[f"send_{checkback.lower()}"](servername, member, self.bot)

            await globals()[f"send_{checkback.lower()}"](servername, member, self.bot)


async def check_status(server, bot):
    with open(fr'{path}/Configs/{server}/welcome.yaml', encoding='utf8') as f:
        data = yaml.load(f, Loader=SafeLoader)

    if data["Config.Enabled"] == True:
        backsend = data["Config.Base"]
        return backsend

    else:
        return False


async def send_text(servername, member, bot):
    with open(rf'{path}/Configs/{servername}/welcome.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)

    channel = bot.get_channel(int(data['Config.Channel']))

    text = data["Config.Text"]["header"] + member.mention + "\n\n" + data["Config.Text"]["text"] + "\n\n" + data["Config.Text"]["footer"]

    await channel.send(text)

    backsend = data["Config.Messages"]["message_send"]
    return backsend


async def send_embed(servername, member, bot):
    with open(rf'{path}/Configs/{servername}/welcome.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)

    channel = bot.get_channel(int(data['Config.Channel']))

    titel = data["Config.Embed"]["title"]
    if "+X+" in titel:
        titel = titel.replace("+X+", member.name)

    descript = data["Config.Embed"]["description"]
    if "+X+" in descript:
        descript = descript.replace("+X+", member.name)
    if "-X-" in descript:
        descript = descript.replace("-X-", member.mention)

    Embed = discord.Embed(
        title = titel,
        description = descript,
        color = int(data["Config.Embed"]["color"], 16)
    )
    Embed.set_thumbnail(url = member.avatar)
    Embed.set_footer(text = data["Config.Embed"]["footer"])

    await channel.send(embed=Embed)

    backsend = data["Config.Messages"]["message_send"]
    return backsend


async def send_picture(servername, member, bot):
    with open(rf'{path}/Configs/{servername}/welcome.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)

    channel = bot.get_channel(int(data['Config.Channel']))

    profile = await load_image_async(str(member.avatar)) 
    welcomer = Editor(rf'{path}/Configs/{servername}/Pictures/welcome.png')
    profile = Editor(profile).resize((int(float(data["Config.Picture"]["profile_size"])), int(float(data["Config.Picture"]["profile_size"])))).circle_image() 
    welcomer.paste(profile.image, (int(float(data["Config.Picture"]["profile_width"])), int(float(data["Config.Picture"]["profile_height"]))))
    
    font = ImageFont.truetype(rf'{path}/Configs/{servername}/Fonts/{data["Config.Picture"]["nametag_font"]}.ttf', int(data["Config.Picture"]["nametag_size"]))
    welcomer.text((int(float(data["Config.Picture"]["nametag_width"])), int(float(data["Config.Picture"]["nametag_height"]))), str(f'{member.name}'), font=font, color="white", align='center') 
    
    font = ImageFont.truetype(rf'{path}/Configs/{servername}/Fonts/{data["Config.Picture"]["timestamp_font"]}.ttf', int(data["Config.Picture"]["timestamp_size"])) 

    time = datetime.now()
    date_time = time.strftime("%d.%m.%Y, %H:%M:%S")

    welcomer.text((int(float(data["Config.Picture"]["timestamp_width"])), int(float(data["Config.Picture"]["timestamp_height"]))), str(f'{date_time}'), font=font, color="white", align='left')  
    
    file = discord.File(fp=welcomer.image_bytes, filename="user_welcome.png")
    await channel.send(file=file)

    backsend = data["Config.Messages"]["message_send"]
    return backsend


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