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

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


class AddServer(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 me an invite to the server. Say ``cancel`` anytime to cancel.")
                try:
                    invite = await self.client.wait_for("message", check=lambda message: message.author == ctx.author
                                                        and message.channel == ctx.channel, timeout=20)
                    if invite.content == "cancel":
                        await ctx.channel.send("Process canceled")
                    else:
                        is_invite = invite.content.find("discord.gg")
                        try:
                            if is_invite > 0:
                                invite = await self.client.fetch_invite(invite.content, with_counts=True)
                                with con:
                                    cur = con.cursor()
                                    server_exists = cur.execute(f"SELECT ID FROM servers WHERE ID = {invite.guild.id}")

                                if server_exists == 0:
                                    try:
                                        if invite.guild.owner == ctx.author:
                                            if invite.max_uses is None:
                                                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,
                                                                                         timeout=60)
                                                if description.content == "cancel":
                                                    await ctx.channel.send("Process canceled. If need be have "
                                                                           "this pre typed")
                                                else:
                                                    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)
                                                    if tags == "cancel":
                                                        await ctx.channel.send("Process canceled")
                                                    else:
                                                        try:
                                                            with con:
                                                                cur = con.cursor()
                                                                cur.execute(f"INSERT INTO servers "
                                                                            f"(ID, name, category, tags, description, raiting, nsfw, invite, sent) "
                                                                            f"VALUES ({invite.guild.id},'"
                                                                            f"{invite.guild.name}','"
                                                                            f"{}"
                                                                            f"{tags.content}','"
                                                                            f"{invite.code}','"
                                                                            f"{description.content}')")
                                                            await ctx.channel.send("Server added successfully")

                                                            embed = discord.Embed(
                                                                colour=discord.Colour.green()
                                                            )
                                                            embed.set_author(name="Server Added")
                                                            embed.add_field(name="ID", value=f"{invite.guild.id}", inline=False)
                                                            embed.add_field(name="Name", value=f"{invite.guild.name}", inline=False)
                                                            embed.add_field(name="Tags", value=f"{tags.content}", inline=False)
                                                            embed.add_field(name="Code", value=f"{invite.code}", inline=False)
                                                            embed.add_field(name="Description", value=f"{description.content}", inline=False)
                                                            await self.client.get_channel(658442038475358238).send(embed=embed)

                                                        except Exception as e:
                                                            await ctx.channel.send("An error has occurred and will be fixed"
                                                                                   "shortly.")
                                                            print(e)
                                                            await self.client.get_channel(656997125627969546).send(e)
                                                            await self.client.\
                                                                get_channel(656997125627969546).\
                                                                send("<@305589587215122432>")
                                        else:
                                            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 ``add server`` in this DM\n"
                                                                   "After ownership is verified the bot can be removed.")

                                    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 ``add server`` in this DM\n"
                                                               "After ownership is verified the bot can be removed.")

                                else:
                                    await ctx.channel.send("It seems this server is already in our databases. "
                                                           "It can be removed with ``remove server``")

                            else:
                                await ctx.channel.send("Invalid invite.")
                        except discord.errors.NotFound:
                            await ctx.channel.send("Invalid invite.")
                except asyncio.TimeoutError:
                    await ctx.channel.send("Process timeout.")


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