import time
import psycopg2
import queue
from LoggingFormatter import logger
import random
from newMarketBot import NewMarketBot
import threading

csgofloat_queue = queue.Queue()
listings_queue = queue.Queue()

def startCsgofloatQueue(all_sessions: list, webshare_ips: list) -> list:
    csgofloat_queue_threads = []

    for i in range(7):
        t = threading.Thread(
            target=handleCsgofloatQueue,
            args=(
                csgofloat_queue,
                webshare_ips,
                all_sessions
            ),
        )
        t.daemon = True
        t.name = "handleCsgofloatQueue" + str(i)
        t.start()
        csgofloat_queue_threads.append(t)
    return csgofloat_queue_threads

def handleCsgofloatQueue(csgofloat_queue: queue.Queue, webshare_ips: list, all_sessions):
    while True:
        if csgofloat_queue.qsize() <= 0:
            time.sleep(random.uniform(0.5, 1))

        else:
            skin_in_db = True
            time.sleep(random.uniform(0.5, 0.7))
            single_elem = csgofloat_queue.get()
            time.sleep(random.uniform(0.5, 0.7))
            price = single_elem[0]
            market_link = single_elem[1]
            single_full_item_name = single_elem[2]
            single_inspect_link = single_elem[3]
            m = single_elem[4]

            try:
                postgresql_conn = psycopg2.connect(
                    database="postgres",
                    user="postgres",
                    password="Berufsorientierung1!",
                    host="23.88.122.57",
                    port="5432",
                )
                postgresql_cur = postgresql_conn.cursor()
                postgresql_cur.execute(
                    "SELECT rank FROM floats WHERE inspect_link = %s",
                    (single_inspect_link,),
                )

                rank_db = postgresql_cur.fetchone()[0]
                logger.info("SKIN IN DB, SKIP")
            except TypeError:
                logger.error("SKIN NOT IN DB, CONTINUE")
                skin_in_db = False
                postgresql_cur.close()
            except (Exception, psycopg2.DatabaseError) as error:
                logger.error(str(error))
            try:
                if postgresql_conn is not None:
                    postgresql_conn.close()
            except Exception as e:
                logger.error(str(e))

            if skin_in_db is False:
                nm = NewMarketBot(
                    "highlow",
                    "Queue Thread",
                    webshare_ips,
                    all_sessions,
                    False,
                    queue.Queue(),
                    queue.Queue(),
                )
                final_listing = nm.singleCheckCsgofloatRank(
                    market_link, single_full_item_name, single_inspect_link, m, price
                )
                if final_listing is None:
                    continue
                elif final_listing == "neger":
                    continue
                else:
                    nm.singleCheckForPotentialBuy(
                        final_listing, single_inspect_link, 1337
                    )
            else:
                continue


def startHandleListingsQueue(all_sessions: list, webshare_ips: list) -> list:
    handle_listings_queue_threads = []
    
    for i in range(7):
        t = threading.Thread(
            target=handleListingsQueue,
            args=(
                listings_queue,
                webshare_ips,
                csgofloat_queue,
                all_sessions
            ),
        )
        t.daemon = True
        t.name = "handleListingsQueue" + str(i)
        t.start()
        handle_listings_queue_threads.append(t)
    return handle_listings_queue_threads

def handleListingsQueue(listings_queue: queue.Queue, webshare_ips, csgofloat_queue, all_sessions):
    while True:
        if listings_queue.qsize() <= 0:
            time.sleep(random.uniform(0.5, 1))

        else:
            bulk_list = listings_queue.get()[0]
            high_low = list(bulk_list[0].values())[0]["high_low"]
            nm = NewMarketBot(
                str(high_low),
                "Best Thread",
                webshare_ips,
                all_sessions,
                False,
                queue.Queue(),
                csgofloat_queue,
            )
            nm.getBestOrWorstSkinsBulk(bulk_list)

