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 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) and (ctx.content.lower() == "add server"):
            try:
                await ctx.channel.send("Send me an invite to the server. Say ``cancel`` anytime to cancel.")
                invite = await self.client.wait_for("message", check=lambda message: message.author == ctx.author
                                                    and message.channel == ctx.channel,
                                                    timeout=20)
                invite = await self.client.fetch_invite(invite.content)
                if invite == "cancel":
                    await ctx.channel.send("Process canceled")
                    return

                categorys = self.client.get_channel(656998225076551680)
                print(categorys.channels)
                category_names = ""
                for channel in categorys.channels:
                    category_names = category_names + '`' + channel.name + '` | '
                await ctx.channel.send("Please slect a category from the following. This will change how the server"
                                       "is shown in the Hub server \n" + category_names)
                category = await self.client.wait_for("message", check=lambda message: message.author == ctx.author
                                                      and message.channel == ctx.channel, timeout=20)
                category = category.content.lower
                if category == "cancel":
                    await ctx.channel.send("Process canceled")
                    return
                for channel in categorys.channels:
                    if category == channel.name:
                        pass
                    else:
                        category = "other"

                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,
                                                  timeout=20)
                if tags == "cancel":
                    await ctx.channel.send("Process canceled")
                    return

                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=20)
                if description == "cancel":
                    await ctx.channel.send("Process canceled")
                    return

                nsfw = 0
                for channel in invite.guild.channels:
                    try:
                        if channel.is_nsfw():
                            nsfw = 1
                    except AttributeError:
                        pass


                try:
                    with con:
                        cur = con.cursor()
                        cur.execute(f"INSERT INTO servers "
                                    f"(ID, name, category, tags, description, nsfw, invite, submitter) "
                                    f"VALUES ({invite.guild.id},'"
                                    f"{invite.guild.name}','"
                                    f"{category}','"
                                    f"{tags.content}','"
                                    f"{description.content}','"
                                    f"{nsfw}','"
                                    f"{invite.code}','"
                                    f"{ctx.author.id}')")
                    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>")

            except asyncio.TimeoutError:
                await ctx.channel.send("Process timeout")
                return


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