from discord.ext import commands
import discord
import pymysql

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

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


class RemoveServer(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() == "remove server":
                await ctx.channel.send("Send the server ID.")
                server_id = await self.client.wait_for("message", check=lambda message: message.author == ctx.author)
                try:
                    server_id = int(server_id.content)
                except ValueError:
                    await ctx.channel.send("Invalid server ID")

                try:
                    member = self.client.get_guild(server_id).get_member(ctx.author.id)
                    if member.guild_permissions.manage_guild:
                        with con:
                            cur = con.cursor()
                            server_exists = cur.execute(f"SELECT ID FROM servers WHERE ID = {server_id}")
                        if server_exists == 0:
                            with con:
                                cur = con.cursor()
                                cur.execute(f"DELETE FROM servers WHERE ID={server_id}")
                        else:
                            await ctx.channel.send("That server could not be found in our databases")

                except AttributeError:
                    await ctx.channel.send("Cannot verify server ownership. "
                                           "Either you are not the guild owner or "
                                           "the bot has not been added to verify ownership.\n"
                                           "Add the bot here : https://discordapp.com/api/oauth2"
                                           "/authorize?client_id=501485906801459200&permissions=1024"
                                           "&scope=bot\n"
                                           "Once the bot is added restart the verification process "
                                           "using ``remove server`` in this DM\n"
                                           "After ownership is verified the bot can be removed.")


# todo

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