#!/home/nonroot/event_scrapy/venv/bin/python3

import discord
from datetime import datetime
from discord.ext.tasks import loop
from time import sleep
from settings import get_connection_event, token

intents = discord.Intents.default()
client = discord.Client(intents=intents)

@client.event
async def on_message(message):
    if message.author.bot:
        return
    if client.user.mentioned_in(message):
        wanted_server = None
        if "ze" in message.content.lower():
            wanted_server = 27015
        elif "mg" in message.content.lower():
            wanted_server = 27017
        elif "zr" in message.content.lower():
            wanted_server = 27016
        if wanted_server is None:
            await message.channel.send("You did not specify a server. Either write ZE, MG or ZR.")
            return
        with get_connection_event() as conn:
            with conn.cursor() as cur:
                sql_statement = f"""
                     select 
                        event_title, event_server, event_maps, event_date, event_time, event_reward, event_url 
                     from unloze_event.event where event_server like '%{wanted_server}%'
                """
                cur.execute(sql_statement)
                res = cur.fetchall()
        event_msg = ""
        for res1 in res:
            event_title = res1[0]
            event_server = res1[1]
            event_maps = res1[2]
            event_date = res1[3]
            event_time = res1[4]
            event_reward = res1[5]
            event_url = res1[6]
            event_msg += f"Title: {event_title}\nServer: {event_server}\nMaps: {event_maps}\nDate: {event_date}\nTime: {event_time}\nRewards: {event_reward}\nURL: {event_url}\n\n"
        await message.channel.send(event_msg)

@loop(seconds = 10)
async def discord_task():
    with get_connection_event() as conn:
        with conn.cursor() as cur:
            #only ze needs the cooldowns set
            sql_statement = f"""
                select event_maps, event_date
                from unloze_event.event e 
                where e.set_map_cooldown is null 
                and e.event_server like '%27015%'
            """
            cur.execute(sql_statement)
            res = cur.fetchone()
            if res is not None:
                event_maps = res[0].split(" ")
                event_date = res[1].strip()
                today_formatted = f"{datetime.now():%d-%m-%Y}".replace("-", "/")
                today_hour = int(f"{datetime.now():%H}")
                #print("today_formatted: ", today_formatted)
                #print("event_date: ", event_date)
                if today_formatted == event_date and today_hour > 10:
                    sql_statement = f"""
                        update unloze_event.event 
                        set set_map_cooldown = true 
                        where event_server like '%27015%'
                    """
                    cur.execute(sql_statement)
                    for r in client.get_all_channels():
                        if r.name == 'rcon-css-ze':
                            print("event_maps: ", event_maps)
                            for map in event_maps:
                                #silly white space none sense 
                                if len(map) > 3:
                                    cooldown_msg = f"""sm_nominate_exclude_time {map} 1 0"""
                                    #adding slight delay
                                    sleep(1)
                                    await r.send(cooldown_msg)
                                    conn.commit()

    with get_connection_event() as conn:
        with conn.cursor() as cur:
            sql_statement = f"""
              select 
                     event_title, event_server, event_maps, event_date, event_time, event_reward, event_url 
              from unloze_event.event where posted_event_on_discord is null
            """
            cur.execute(sql_statement)
            res = cur.fetchall()
            if res is not None:
                for res1 in res:
                    event_title = res1[0]
                    event_server = res1[1]
                    event_maps = res1[2]
                    event_date = res1[3]
                    event_time = res1[4]
                    event_reward = res1[5]
                    event_url = res1[6]

                    sql_statement = f"""
                         update unloze_event.event 
                         set posted_event_on_discord = 1 
                         where event_title = %s
                    """
                    cur.execute(sql_statement, [event_title])
                    try:
                        event_msg = f"**- New Event Posted! -**\nTitle: {event_title}\nServer: {event_server}\nMaps: {event_maps}\nDate: {event_date}\nTime: {event_time}\nRewards: {event_reward}\nURL: {event_url}\n\n"
                        for r in client.get_all_channels():
                            if r.name == 'events':
                                await r.send(event_msg)
                                conn.commit()
                    except Exception:
                        import traceback
                        error_msg = traceback.format_exc()
                        print("traceback happened: ", error_msg)

def main():
    discord_task.start()
    client.run(token)

if __name__ == '__main__':
    main()
