from discord.ext import commands
import discord
import pymysql
import asyncio

password = open("../../../../sqlPass.txt", 'r')

con = pymysql.connect(host='localhost',
                      user='Bot',
                      password=f'{password}',
                      db='serverIDs',
                      charset='utf8mb4',
                      cursorclass=pymysql.cursors.DictCursor)


class NewServer(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, ctx):
        if isinstance(ctx.channel, discord.DMChannel):
            if ctx.content.lower() == "add server":
                await ctx.channel.send("Send an invite to the server")
                invite = await self.client.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == ctx.channel)
                is_invite = invite.content.find("discord.gg")
                if is_invite > 0:
                    invite = await self.client.fetch_invite(invite.content, with_counts=True)
                    print(invite.max_uses)
                    if not (invite.max_uses is None):
                        await ctx.channel.send("Please send a invite with no max uses")
                    elif invite.inviter != ctx.author:
                        await ctx.channel.send("Please be the creator of the invite")
                    elif invite.inviter != invite.guild.owner:
                        await ctx.channel.send("Please be the owner of this server")
                    else:
                        await ctx.channel.send("Please send a description of the server")
                        description = await self.client.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == ctx.channel)
                        await ctx.channel.send("Please send a list of tags separated by a comma(,) no spaces")
                        tags = await self.client.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == ctx.channel)
                        with con:
                            cur = con.cursor()
                            cur.execute(f"INSERT INTO servers (ID, name, tags, invite, description) VALUES ({invite.guild.id},'{invite.guild.name}','{tags.content}','{invite.code}','{description.content}')")
                else:
                    await ctx.channel.send("Invalid invite")


def setup(client):
    client.add_cog(NewServer(client))
