#!/home/nonroot/handle_event_rewards/venv/bin/python3
from settings import (get_connection_events, api_key)
import requests

unloze_user_upgrade_api = f"https://unloze.com/api/private_user_upgrade_api.php?api_key={api_key}&steam_id="

def get_all_pending_event_rewards():
    with get_connection_events() as conn:
        with conn.cursor(buffered=True) as cur:
            sql_statement = """
                select steamid, event_reward_days 
                    from unloze_event.rewards
                where is_processed is false
            """
            cur.execute(sql_statement)
            res = cur.fetchall()
    conn.close()
    return res

def update_is_procssed():
    with get_connection_events() as conn:
        with conn.cursor(buffered=True) as cur:
            sql_statement = """
                update unloze_event.rewards set is_processed = true where is_processed is false
            """
            cur.execute(sql_statement)
            conn.commit() #pretty gay how contextmanager cant commit and close itself like in psycopg2
    conn.close()

def steamid_to_commid(steamid):
    steamid64ident = 76561197960265728
    sid_split = steamid.split(':')
    commid = int(sid_split[2]) * 2
    if sid_split[1] == '1':
      commid += 1
    commid += steamid64ident
    return commid

def update_steam_id_has_no_forum_account_with_steam(steamid):
    with get_connection_events() as conn:
        with conn.cursor(buffered=True) as cur:
            sql_statement = """
                update unloze_event.rewards 
                    set has_no_forum_account_with_associated_steam = true 
                where has_no_forum_account_with_associated_steam is not true
                   and steamid = %s
            """
            cur.execute(sql_statement, [steamid])
            conn.commit() #pretty gay how contextmanager cant commit and close itself like in psycopg2
    conn.close()

def reward_vip_to_event_winners(res):
    for result in res:
        steamid = result[0]
        days_rewarded = result[1]
        steam_community_id = steamid_to_commid(steamid)

        r = requests.get(f"{unloze_user_upgrade_api}{steam_community_id}&days_reward={days_rewarded}")
        #print("r.url: ", r.url)
        if r.content.decode('utf8').startswith("NOACCOUNT"): #not registed with associated steam account
            update_steam_id_has_no_forum_account_with_steam(steamid)

def main():
    res = get_all_pending_event_rewards()
    #send request to xenforo for giving vip time
    reward_vip_to_event_winners(res)
    update_is_procssed() #we took them all out so we just update all rows where is_processed is false.

if __name__ == '__main__':
    main()