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

import requests
from datetime import datetime
from time import sleep
from settings import get_connection_event

# Stoat configuration
BOT_TOKEN = ""
API_URL = ""
EVENTS_CHANNEL_ID = ""
RCON_CHANNEL_ID = ""

def stoat_send_message(channel_id, content):
    """Send a message to a Stoat channel"""
    try:
        response = requests.post(
            f"{API_URL}/channels/{channel_id}/messages",
            headers={
                'x-bot-token': BOT_TOKEN,
                'Content-Type': 'application/json'
            },
            json={'content': content}
        )
        response.raise_for_status()
        return response.json()
    except Exception as e:
        print(f"Error sending message: {e}")
        return None

def check_and_set_cooldowns():
    """Check for events and set map cooldowns"""
    with get_connection_event() as conn:
        with conn.cursor() as cur:
            # Only ZE needs the cooldowns set
            sql_statement = """
                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}")
                
                if today_formatted == event_date and today_hour > 10:
                    sql_statement = """
                        update unloze_event.event 
                        set set_map_cooldown = true 
                        where event_server like '%27015%'
                    """
                    cur.execute(sql_statement)
                    
                    print("event_maps: ", event_maps)
                    for map_name in event_maps:
                        # Silly white space nonsense
                        if len(map_name) > 3:
                            cooldown_msg = f"sm_nominate_exclude_time {map_name} 1 0"
                            # Adding slight delay
                            sleep(1)
                            stoat_send_message(RCON_CHANNEL_ID, cooldown_msg)
                    
                    conn.commit()

def check_and_post_events():
    """Check for new events and post them"""
    with get_connection_event() as conn:
        with conn.cursor() as cur:
            sql_statement = """
                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 = """
                        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"
                        stoat_send_message(EVENTS_CHANNEL_ID, event_msg)
                        conn.commit()
                    except Exception:
                        import traceback
                        error_msg = traceback.format_exc()
                        print("traceback happened: ", error_msg)


def main_l():
    import time
    
    print("Stoat Event Bot started!")
    
    try:
        check_and_set_cooldowns()
        check_and_post_events()
    except Exception as e:
        import traceback
        print(f"Error in main: {traceback.format_exc()}")
        

def main():
    main_l()

if __name__ == '__main__':
    main()

