#!/home/nonroot/stoat_admin_activity_ze/venv/bin/python3
from settings import get_connection_unloze_playtime, get_connection_sourceban, stoat_token, stoat_url
import requests
from datetime import datetime

def get_admin_list_ze():
    with get_connection_sourceban() as conn:
        with conn.cursor() as cur:
            #32 means ze and -1 means a game category, i.e css.
            sql_statement = f"""
                select unique(sa.user), sa.authid
                    from unloze_sourceban.sb_admins sa 
                inner join unloze_sourceban.sb_admins_servers_groups ss 
                    on sa.aid = ss.admin_id 
                where sa.srv_group not in ('Game-Donator', '')
                    and (ss.server_id = 32 or ss.srv_group_id != -1)
                order by sa.`user` 
            """
            cur.execute(sql_statement)
            res = cur.fetchall()

    if res is not None:
        with get_connection_unloze_playtime() as conn:
            with conn.cursor() as cur:
                for index, result in enumerate(res):
                    player_time = 0
                    sql_statement = f"""
                        select pt.ze_time
                            from unloze_playtimestats.player_time pt 
                            where pt.steam_id = %s
                    """
                    cur.execute(sql_statement, [result[1]])
                    res1 = cur.fetchall()
                    for result1 in res1:
                        player_time += result1[0]
                    res[index] = res[index] + (player_time, )
    return res

def get_admin_activity_ze():
    with get_connection_unloze_playtime() as conn:
        with conn.cursor() as cur:
            sql_statement = f"""
                select * from unloze_playtimestats.admin_activity_ze
            """
            cur.execute(sql_statement)
            res = cur.fetchall()
    return res

def send_message_to_stoat(admin_activity, admins):
    message = ""
    admins_ordered_by_time = {}
    if admin_activity:
        took_time = False
        admins_with_no_activity_found = False
        for res in admin_activity:
            name = res[0]
            steam_id = res[1]
            playtime = res[2]
            date_began = res[3]
            if not took_time:
                took_time = True
                message += f"Started Time Tracking from **{date_began} until {datetime.now()}** for Zombie Escape:\n\n"

            for admin in admins:
                if admin[1] == steam_id:
                    playtime_since_last_week = admin[2] - playtime
                    hours_server = int((playtime_since_last_week / 60) / 60)
                    minutes_server = int((playtime_since_last_week / 60) % 60)
                    admins_ordered_by_time[steam_id] = [name, playtime_since_last_week, hours_server, minutes_server]
                    break

        sorted_admins = sorted(admins_ordered_by_time.items(), key=lambda x: x[1][1], reverse=True)
        for steam_id, data in sorted_admins:
            name, playtime_since_last_week, hours, minutes = data
            if not admins_with_no_activity_found and playtime_since_last_week == 0:
                admins_with_no_activity_found = True
                message += "///**Admins Below here have no activity at all**\\\\\ \n\n\n"
            message += f"{name} ({steam_id}) Playtime: {hours} hours and {minutes} minutes.\n\n"
        #print(message)
    else:
        message = "This is the beginning of tracking admin activity on ze. the Intention is once every week to report how much playtime each admin and staff had on zombie escape. Tracking starts today and the first results will presumably be posted here on Sunday. Going forward probably every sunday."

    headers = {
        "x-bot-token": f"{stoat_token}",
        "Content-Type": "application/json"
    }

    message_chunks = split_message_by_lines(message)
    for chunk in message_chunks:
        data = {
            "content": chunk 
        }

        response = requests.post(stoat_url, headers=headers, json=data)
        if response.status_code > 299:
            print(response.status_code, " ", response.text)

#AI slop function
def split_message_by_lines(message, limit=1900):
    lines = message.split('\n')
    chunks = []
    current_chunk = ""

    for line in lines:
        # Check if adding this line (plus a newline) exceeds the limit
        if len(current_chunk) + len(line) + 1 > limit:
            if current_chunk:
                chunks.append(current_chunk.strip())
            current_chunk = line + '\n'
        else:
            current_chunk += line + '\n'
    
    # Add the final remaining chunk
    if current_chunk:
        chunks.append(current_chunk.strip())
        
    return chunks

def truncate_admin_activity_ze():
    with get_connection_unloze_playtime() as conn:
        with conn.cursor() as cur:
            sql_statement = f"""
                truncate table unloze_playtimestats.admin_activity_ze
            """
            cur.execute(sql_statement)
            conn.commit()

def insert_admin_activity_ze(admins):
    with get_connection_unloze_playtime() as conn:
        with conn.cursor() as cur:
            for admin in admins:
                sql_statement = f"""
                    INSERT INTO unloze_playtimestats.admin_activity_ze
                        (name, steamid, ze_time_start_week, inserted_on)
                        VALUES(%s, %s, %s, current_timestamp());
                """
                cur.execute(sql_statement, [admin[0], admin[1], admin[2]])
                conn.commit()

def main():
    admins = get_admin_list_ze()
    admin_activity = get_admin_activity_ze()

    send_message_to_stoat(admin_activity, admins)

    truncate_admin_activity_ze()
    insert_admin_activity_ze(admins)

if __name__ == '__main__':
    main()
