import json
import urllib.parse
import time
import random
from bluegems import bluegems
from RequestManager import RequestManager
import HelperFunctions
import psycopg2
import queue
from FinalListing import FinalListing
import topfloatdb
from LoggingFormatter import logger
import SeleniumExecutor


class NewMarketBot(object):
    def __init__(
        self,
        high_low,
        weapon_name,
        webshare_ips,
        all_sessions,
        extended_scrape,
        listings_queue: queue.Queue,
        csgofloat_queue: queue.Queue,
    ):
        self.high_low = high_low
        self.weapon_name = weapon_name
        self.listings_url_set = set()
        self.inspect_links_list = []
        self.listings_info_list = []
        self.listings_info_dict = {}
        self.best_or_worst_skins = []
        self.webshare_ips = webshare_ips
        self.extended_scrape = extended_scrape
        self.RequestManager = RequestManager(all_sessions, webshare_ips)
        self.listings_queue = listings_queue
        self.csgofloat_queue = csgofloat_queue
        self.inspect_server_url = "http://23.88.122.57:1337/"

    def getHashedNameListHighOrLow(self):
        end = False
        count = 0
        repeat_counter = 0

        if self.high_low == "high":
            wear = 4
        elif self.high_low == "low":
            wear = 0

        if self.weapon_name == "gloves":
            all_skins_url = (
                "https://steamcommunity.com/market/search/render?currency=3&norender=1/?query=&start={0}"
                "&count=100&search_descriptions=0&sort_column=price&sort_dir=asc&appid=730&category_730_ItemSet"
                "%5B%5D=any&category_730_ProPlayer%5B%5D=any&category_730_StickerCapsule%5B%5D=any"
                "&category_730_TournamentTeam%5B%5D=any&category_730_Weapon%5B%5D=any&category_730_Exterior"
                "%5B%5D=tag_WearCategory{1}&category_730_Rarity%5B%5D=tag_Rarity_Ancient".format(
                    count, wear
                )
            )

        else:
            all_skins_url = (
                "https://steamcommunity.com/market/search/render?currency=3&norender=1/?query=&start={1}"
                "&count=100&search_descriptions=0&sort_column=price&sort_dir=asc&appid=730&category_730_ItemSet"
                "%5B%5D=any&category_730_ProPlayer%5B%5D=any&category_730_StickerCapsule%5B%5D=any"
                "&category_730_TournamentTeam%5B%5D=any&category_730_Weapon%5B%5D={1}"
                "&category_730_Exterior%5B%5D=tag_WearCategory{2}".format(
                    count, self.weapon_name, wear
                )
            )

        while not end:
            try:
                response = self.RequestManager.getRequestAllAvailableProxies(
                    all_skins_url, skins_or_inspect_links="skins"
                )
                if response is None:
                    time.sleep(5)
                    continue
                if isinstance(response, str):
                    json_page = json.loads(response.text)
                else:
                    json_page = response.json()
            except Exception as e:
                logger.critical("Exception in getHashedNameListHighOrLow: " + str(e))
                continue

            repeat_counter += 1

            if repeat_counter >= 2:
                random_time = random.uniform(0.5, 1.5)
                time.sleep(repeat_counter * random_time)

            if repeat_counter > 20:
                end = True
                logger.critical("json_page failed 20 times, skipping")
                continue

            if json_page == None:
                continue

            if len(json_page["results"]) == 0:
                continue

            if json_page["total_count"] < json_page["pagesize"]:
                end = True
            else:
                logger.critical(str(self.weapon_name) + ": total_count < pagesize")

            for i in json_page["results"]:
                if (
                    "USP-S | 027" in i["name"]
                    or "M249 | Hypnosis" in i["name"]
                    or "SCAR-20 | Trail Blazer" in i["name"]
                    or "MP5-SD | Statics" in i["name"]
                    or "R8 Revolver | Tango" in i["name"]
                    or "Desert Eagle | Calligraffiti" in i["name"]
                    or "AUG | Luxe Trim" in i["name"]
                    or "MAC-10 | Saibā Oni" in i["name"]
                    or "Dual Berettas | Hydro Strike" in i["name"]
                    or "M4A4 | Turbine" in i["name"]
                    or "SSG 08 | Rapid Transit" in i["name"]
                    or "P90 | Randy Rush" in i["name"]
                    or "UMP-45 | Neo-Noir" in i["name"]
                    or "P250 | Epicenter" in i["name"]
                    or "AK-47 | The Outsiders" in i["name"]
                    or "Glock-18 | Gold Toof" in i["name"]
                    or "M4A1-S | Vaporwave" in i["name"]
                    or "Desert Eagle | Heat Treated" in i["name"]
                    or "M4A1-S | Fade" in i["name"]
                    or "Galil AR | Rainbow Spoon" in i["name"]
                    or "Glock-18 | AXIA" in i["name"]
                    or "Five-SeveN | Heat Treated" in i["name"]
                    or "UMP-45 | Crimson Foil" in i["name"]
                    or "MP9 | Arctic Tri-Tone" in i["name"]
                    or "USP-S | Alpine Camo" in i["name"]
                    or "P250 | Small Game" in i["name"]
                    or "SSG 08 | Zeno" in i["name"]
                    or "Nova | Yorkshire" in i["name"]
                    or "AK-47 | Olive Polycam" in i["name"]
                    or "MAG-7 | Wildwood" in i["name"]
                    or "PP-Bizon | Cold Cell" in i["name"]
                    or "MP5-SD | Savannah Halftone" in i["name"]
                    or "Tec-9 | Tiger Stencil" in i["name"]
                    or "FAMAS | Half Sleeve" in i["name"]
                    or "AK-47 | B the Monster" in i["name"]
                    or "Zeus x27 | Dragon Snore" in i["name"]
                    or "AWP | Crakow!" in i["name"]
                    or "XM1014 | Monster Melt" in i["name"]
                    or "Dual Berettas | Sweet Little Angels" in i["name"]
                    or "AUG | Eye of Zapems" in i["name"]
                    or "Nova | Wurst Hölle" in i["name"]
                    or "Glock-18 | Teal Graf" in i["name"]
                    or "Galil AR | Metallic Squeezer" in i["name"]
                    or "MAC-10 | Pipsqueak" in i["name"]
                    or "Five-SeveN | Midnight Paintover" in i["name"]
                    or "MP5-SD | Neon Squeezer" in i["name"]
                    or "Desert Eagle | Tilted" in i["name"]
                    or "Negev | Wall Bang" in i["name"]
                    or "M4A1-S | Wash me plz" in i["name"]
                    or "P90 | Wash me" in i["name"]
                    or "AWP | CMYK" in i["name"]
                    or "Desert Eagle | Starcade" in i["name"]
                    or "AUG | Lil' Pig" in i["name"]
                    or "M4A4 | Polysoup" in i["name"]
                    or "P90 | Attack Vector" in i["name"]
                    or "CZ75-Auto | Slalom" in i["name"]
                    or "AK-47 | Crossfade" in i["name"]
                    or "SG 553 | Berry Gel Coat" in i["name"]
                    or "SCAR-20 | Wild Berry" in i["name"]
                    or "Galil AR | NV" in i["name"]
                    or "MP7 | Astrolabe" in i["name"]
                    or "XM1014 | Halftone Shift" in i["name"]
                    or "FAMAS | Halftone Wash" in i["name"]
                    or "P2000 | Coral Halftone" in i["name"]
                    or "SSG 08 | Halftone Whorl" in i["name"]
                    or "M249 | Spectrogram" in i["name"]
                ):
                    logger.info("SKIPPING NEW SKIN: " + str(i["name"]))
                    # HelperFunctions.writeErrorToLog("SKIPPING NEW SKIN: " + str(i["name"]))
                    continue
                if i["sell_listings"] == 0:
                    logger.critical("NO LISTINGS FOR " + str(i["name"]))
                    continue
                listings_url = (
                    "https://steamcommunity.com/market/listings/730/"
                    + urllib.parse.quote(str(i["name"]).encode("utf-8"))
                    + "/render/?query="
                )
                self.listings_url_set.add(listings_url)
            count += 100

        if self.high_low == "high":
            with open("skins_high_new.json") as json_file_high:
                skins_high = json.load(json_file_high)
                if self.weapon_name in skins_high:
                    for skin in skins_high[self.weapon_name]:
                        full_skin_name = str(skin[0]) + " (" + str(skin[2]) + ")"
                        listings_url = (
                            "https://steamcommunity.com/market/listings/730/"
                            + urllib.parse.quote(str(full_skin_name).encode("utf-8"))
                            + "/render/?query="
                        )
                        self.listings_url_set.add(listings_url)

        if self.high_low == "low":
            with open("skins_low_new.json") as json_file_low:
                skins_low = json.load(json_file_low)
                if self.weapon_name in skins_low:
                    for skin in skins_low[self.weapon_name]:
                        full_skin_name = str(skin[0]) + " (" + str(skin[1]) + ")"
                        listings_url = (
                            "https://steamcommunity.com/market/listings/730/"
                            + urllib.parse.quote(str(full_skin_name).encode("utf-8"))
                            + "/render/?query="
                        )
                        self.listings_url_set.add(listings_url)

    def buildInspectLinksList(self):
        time.sleep(random.uniform(0.2, 0.5))
        for i in self.listings_url_set:
            if i == "" or i == None or i == "\n":
                logger.critical("i IS EMPTY????")
                continue
            end = False
            repeat_counter_overall = 0
            start = 0
            while not end:
                repeat_counter_overall += 1

                if repeat_counter_overall >= 2:
                    random_time = random.uniform(1, 4)
                    time.sleep(repeat_counter_overall + random_time)

                if repeat_counter_overall > 15:
                    end = True
                    logger.critical("listings_page_json failed 15 times with " + str(i))

                single_listings_url = (
                    str(i) + "&start=" + str(start) + "&count=100&currency=3"
                )
                encoded_market_name = urllib.parse.urlparse(
                    single_listings_url
                ).path.split("/")[4]
                if HelperFunctions.checkIfSkinExcluded(encoded_market_name) is True:
                    end = True
                    continue

                listings_page_json = self.getInspectLinks(
                    single_listings_url
                )

                if listings_page_json == None:
                    time.sleep(2)
                    continue

                if "listinginfo" not in listings_page_json:
                    time.sleep(2)
                    continue

                if listings_page_json["listinginfo"] is None:
                    time.sleep(2)
                    continue

                end = True

                list_for_queue = []
                try:
                    for listing_id in listings_page_json["listinginfo"].keys():
                        listing_info = listings_page_json["listinginfo"][
                            str(listing_id)
                        ]
                        all_params = HelperFunctions.buildListingInfoList(
                            listing_info=listing_info, high_low=self.high_low
                        )
                        list_for_queue.append({str(listing_id): all_params})
                    self.listings_queue.put([list_for_queue])
                    time.sleep(1)
                except Exception as e:
                    logger.critical("buildInspectLinksList(): " + str(e))
        return None
    
    def getInspectLinks(self, single_listings_url: str):
        response = self.RequestManager.getRequestAllAvailableProxies(
            single_listings_url, False
        )
        if response is None:
            return None

        if isinstance(response, str):
            listings_page_json = json.loads(response)
        else:
            listings_page_json = response.json()
        return listings_page_json


    def getBestOrWorstSkinsBulk(self, splitted_bulk):
        if splitted_bulk == None or len(splitted_bulk) == 0:
            logger.error("getBestOrWorstSkinsBulk(): splitted_bulk is None or len is 0")
            return None
        new_splitted_bulk = HelperFunctions.getSplittedBulkList(splitted_bulk)
        if isinstance(new_splitted_bulk, tuple):
            if new_splitted_bulk[0] == None:
                logger.critical(
                    "Exception with HelperFunctions.getSplittedBulkList(splitted_bulk): "
                    + str(new_splitted_bulk[1])
                )
        for j in splitted_bulk:
            self.listings_info_dict[list(j.keys())[0]] = list(j.values())[0]
        best_float = 0
        best_float_id = 0
        listing_to_check = None
        end = False
        while not end:
            try:
                bulk_response_json = self.RequestManager.postRequestNaked(
                    self.inspect_server_url + "bulk", _json=new_splitted_bulk
                ).json()
            except Exception as e:
                time.sleep(5)
                logger.critical("Exception in getBestOrWorstSkinsBulk: " + str(e))
                continue

            if bulk_response_json == None:
                continue

            if len(splitted_bulk) == 0:
                end = True
                continue

            if "error" in bulk_response_json:
                time.sleep(2)
                continue

            if len(bulk_response_json) == 0:
                continue

            end = True
            time.sleep(0.1)

            for j in bulk_response_json:
                if "error" in bulk_response_json[j]:
                    continue
                if "m" not in bulk_response_json[j]:
                    continue

                if bulk_response_json[j]["s"] == "0":
                    single_inspect_server_url = (
                        self.inspect_server_url
                        + "?url=steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20"
                        + "M"
                        + str(bulk_response_json[j]["m"])
                        + "A"
                        + str(bulk_response_json[j]["a"])
                        + "D"
                        + str(bulk_response_json[j]["d"])
                    )
                if bulk_response_json[j]["m"] == "0":
                    single_inspect_server_url = (
                        self.inspect_server_url
                        + "?url=steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20"
                        + "S"
                        + str(bulk_response_json[j]["s"])
                        + "A"
                        + str(bulk_response_json[j]["a"])
                        + "D"
                        + str(bulk_response_json[j]["d"])
                    )

                if "floatid" not in bulk_response_json[j]:
                    HelperFunctions.floatidNotInBulk(
                        single_inspect_server_url=single_inspect_server_url,
                        bulk_at_j=bulk_response_json[j],
                        request_manager=self.RequestManager,
                    )

                item_encoded = HelperFunctions.encodeItemName(
                    str(bulk_response_json[j]["full_item_name"])
                )

                self.checkForStickers(bulk_response_json[j], item_encoded)
                self.checkForBluegem(bulk_response_json[j], item_encoded)

                if self.high_low == "high":
                    if float(bulk_response_json[j]["floatvalue"]) > best_float:
                        best_float = float(bulk_response_json[j]["floatvalue"])
                        best_float_id = j

                if self.high_low == "low":
                    if best_float == 0:
                        best_float = bulk_response_json[j]["max"]
                    if float(bulk_response_json[j]["floatvalue"]) < best_float:
                        best_float = float(bulk_response_json[j]["floatvalue"])
                        best_float_id = j
                listing_to_check = bulk_response_json[best_float_id]

        #logger.error("LISTING TO CHECK: " + str(listing_to_check))
        if listing_to_check != None:
            item_encoded = HelperFunctions.encodeItemName(
                str(listing_to_check["full_item_name"])
            )

            price = self.listings_info_dict[listing_to_check["m"]]["price"]
            market_link = HelperFunctions.generateMarketLink(
                item_encoded=item_encoded,
                m=listing_to_check["m"],
                a=listing_to_check["a"],
            )
            single_full_item_name = listing_to_check["full_item_name"]
            #single_inspect_link = self.listings_info_dict[listing_to_check["m"]]["link"]
            #if single_inspect_link is None:
            single_inspect_link = HelperFunctions.generateInspectLink(
                m=listing_to_check["m"],
                s=listing_to_check["s"],
                a=listing_to_check["a"],
                d=listing_to_check["d"],
            )

            if self.high_low == "high":
                if (
                    self.checkForHighRank(
                        listing_to_check,
                        single_full_item_name,
                        price,
                        market_link,
                        single_inspect_link,
                    )
                    is None
                ):
                    return None

            if self.high_low == "low":
                if (
                    self.checkForLowRank(
                        listing_to_check,
                        single_full_item_name,
                        price,
                        market_link,
                        single_inspect_link,
                    )
                    is None
                ):
                    return None

        else:
            logger.critical(
                "LISTING TO CHECK IS NONE, WAT????????? " + str(splitted_bulk)
            )

    def checkForStickers(self, bulk_response_json_j, item_encoded):
        sticki = bulk_response_json_j["stickers"]
        for sticker in sticki:
            if "material" in sticker:
                if str(sticker["material"]).startswith("emskatowice2014"):
                    if "Holo" in str(sticker["name"]):
                        market_link = (
                            "https://steamcommunity.com/market/listings/730/"
                            + str(item_encoded)
                            + "#buylisting|"
                            + str(bulk_response_json_j["m"])
                            + "|730|2|"
                            + str(bulk_response_json_j["a"])
                        )
                        single_sticki = {}
                        single_sticki[str(bulk_response_json_j["full_item_name"])] = [
                            "Stickomat",
                            self.listings_info_dict[bulk_response_json_j["m"]]["price"],
                            market_link,
                        ]
                        HelperFunctions.writeSingleAnyToFile(
                            single_sticki, "stickers.txt"
                        )
                        final_listing = FinalListing(
                            full_item_name=str(bulk_response_json_j["full_item_name"]),
                            market_url=str(market_link),
                            inspect_link=self.listings_info_dict[
                                bulk_response_json_j["m"]
                            ]["link"],
                            rank=str("Stickomat"),
                            price=self.listings_info_dict[bulk_response_json_j["m"]][
                                "price"
                            ],
                        )
                        self.singleCheckForPotentialBuy(final_listing)

    def checkForBluegem(self, bulk_response_json_j, item_encoded):
        if "item_name" in bulk_response_json_j:
            if bulk_response_json_j["item_name"] == "Case Hardened":
                pattern = bulk_response_json_j["paintseed"]
                if str(self.weapon_name) in bluegems:
                    if str(pattern) in bluegems[str(self.weapon_name)]:
                        market_link = (
                            "https://steamcommunity.com/market/listings/730/"
                            + str(item_encoded)
                            + "#buylisting|"
                            + str(bulk_response_json_j["m"])
                            + "|730|2|"
                            + str(bulk_response_json_j["a"])
                        )
                        single_bluegem = {}
                        single_bluegem[str(bulk_response_json_j["full_item_name"])] = [
                            "BlueGem",
                            self.listings_info_dict[bulk_response_json_j["m"]]["price"],
                            market_link,
                        ]
                        HelperFunctions.writeSingleAnyToFile(
                            single_bluegem, "bluegems.txt"
                        )
                        final_listing = FinalListing(
                            full_item_name=str(bulk_response_json_j["full_item_name"]),
                            market_url=str(market_link),
                            inspect_link=self.listings_info_dict[
                                bulk_response_json_j["m"]
                            ]["link"],
                            rank=str("Stickomat"),
                            price=self.listings_info_dict[bulk_response_json_j["m"]][
                                "price"
                            ],
                        )
                        self.singleCheckForPotentialBuy(final_listing)

    def checkForHighRank(
        self,
        listing_to_check,
        single_full_item_name,
        price,
        market_link,
        single_inspect_link,
    ):
        if "high_rank" in listing_to_check:
            if listing_to_check["high_rank"] > 5:
                return None
            else:
                if self.alreadyChecked(single_inspect_link=single_inspect_link) is True:
                    return None
                #logger.info("pass for now, but change")
                else:
                    end = False
                    while not end:
                        try:
                            csfloat_iteminfo = SeleniumExecutor.getItemInfo(str(single_inspect_link))
                            #logger.critical(csfloat_iteminfo)
                            #csfloat_iteminfo = json.dumps(csfloat_iteminfo_no_json)
                        except Exception as e:
                            logger.critical(str(e))
                            continue
                        if csfloat_iteminfo is None:
                            logger.error("csfloat_iteminfo is None, repeating...")
                            time.sleep(2)
                            continue
                        logger.info(csfloat_iteminfo)
                        logger.info(str(single_inspect_link))
                        if "error" in csfloat_iteminfo:
                            logger.info(str(single_inspect_link))
                        if "iteminfo" in csfloat_iteminfo:
                            if "high_rank" in csfloat_iteminfo["iteminfo"]:
                                if csfloat_iteminfo["iteminfo"]["high_rank"] < 6:
                                    final_listing = FinalListing(
                                        full_item_name=single_full_item_name,
                                        market_url=str(market_link),
                                        inspect_link=single_inspect_link,
                                        rank=str(csfloat_iteminfo["iteminfo"]["high_rank"]),
                                        price=price,
                                    )
                                    self.singleCheckForPotentialBuy(
                                        final_listing=final_listing,
                                        inspect_link=single_inspect_link,
                                        rank=csfloat_iteminfo["iteminfo"]["high_rank"],
                                    )
                            end = True

    def checkForLowRank(
        self,
        listing_to_check,
        single_full_item_name,
        price,
        market_link,
        single_inspect_link,
    ):
        if "low_rank" in listing_to_check:
            if listing_to_check["low_rank"] > 5:
                return None
            else:
                if self.alreadyChecked(single_inspect_link=single_inspect_link) is True:
                    return None
                else:
                    end = False
                    while not end:
                        try:
                            csfloat_iteminfo = SeleniumExecutor.getItemInfo(str(single_inspect_link))
                            #csfloat_iteminfo = json.dumps(csfloat_iteminfo_no_json)
                        except Exception as e:
                            logger.critical(str(e))
                            continue
                        if csfloat_iteminfo is None:
                            logger.error("csfloat_iteminfo is None, repeating...")
                            time.sleep(2)
                            continue
                        logger.info(csfloat_iteminfo)
                        if "iteminfo" in csfloat_iteminfo:
                            if "low_rank" in csfloat_iteminfo["iteminfo"]:
                                if csfloat_iteminfo["iteminfo"]["low_rank"] < 6:
                                    final_listing = FinalListing(
                                        full_item_name=single_full_item_name,
                                        market_url=str(market_link),
                                        inspect_link=single_inspect_link,
                                        rank=str(csfloat_iteminfo["iteminfo"]["low_rank"]),
                                        price=price,
                                    )
                                    self.singleCheckForPotentialBuy(
                                        final_listing=final_listing,
                                        inspect_link=single_inspect_link,
                                        rank=csfloat_iteminfo["iteminfo"]["low_rank"],
                                    )
                            end = True

    def alreadyChecked(self, single_inspect_link):
        already_in_db = False
        with topfloatdb.db_cursor() as cur:
            cur.execute(
                    "SELECT inspect_link FROM checked WHERE inspect_link = %s",
                    (single_inspect_link,),
                )
            
            try:
                ret = len(cur.fetchall())
                if ret > 0:
                    already_in_db = True
                    logger.info(str(single_inspect_link) + " already in DB, skipping.")
                else:
                    try:
                        already_in_db = False
                        cur.execute(
                            "INSERT INTO checked(inspect_link) VALUES(%s)",
                            (single_inspect_link,),
                        )
                    except Exception as e:
                        logger.error(str(e))
                        HelperFunctions.writeErrorToLog(str(e))
            except Exception as e:
                logger.error(str(e))
                HelperFunctions.writeErrorToLog(str(e))
                return False
        return already_in_db
    
    def checkDBForFloat(self, full_item_name, floatvalue):
        with topfloatdb.db_cursor() as cur:
            if self.high_low == "high":
                cur.execute(
                    "SELECT float FROM sih_floats WHERE market_hash_name = %s ORDER BY float DESC LIMIT 5",
                    (full_item_name,),
                )
                top5_floats = cur.fetchall()
            if self.high_low == "low":
                cur.execute(
                    "SELECT float FROM sih_floats WHERE market_hash_name = %s ORDER BY float ASC LIMIT 5",
                    (full_item_name,),
                )
                top5_floats = cur.fetchall()

            if len(top5_floats) == 0:
                logger.error("NO TOP 5 FLOATS FOUND FOR: " + str(full_item_name))
                return None

            rank = 1
            for topfloat in top5_floats:
                if self.high_low == "high":
                    if floatvalue > topfloat[0]:
                        return rank
                if self.high_low == "low":
                    if floatvalue < topfloat[0]:
                        return rank
                rank += 1
        return 1337

    def singleCheckForPotentialBuy(
        self, final_listing: FinalListing, inspect_link="", rank=0
    ):
        single_cheap_top_skin = {}
        end = False
        repeat_counter = 0
        while not end:
            lowest_price = 0
            repeat_counter += 1
            try:
                price_overview_page = self.RequestManager.getRequestAllAvailableProxies(
                    "https://steamcommunity.com/market/priceoverview/?market_hash_name="
                    + HelperFunctions.encodeAidsItemName(final_listing.full_item_name)
                    + "&appid=730&currency=3",
                    False, "price"
                )
                if price_overview_page is None:
                    if repeat_counter > 10:
                        end = True
                        logger.error(
                            "Couldn't get price for "
                            + str(final_listing.full_item_name)
                            + " after 10 times, skipping for now"
                        )
                    continue

                price_overview_json = json.loads(price_overview_page.text)
            except Exception as e:
                logger.critical("Exception in singleCheckForPotentialBuy: " + str(e))
                continue

            if price_overview_json == None:
                continue

            if "lowest_price" in price_overview_json:
                lowest_price = price_overview_json["lowest_price"]
                lowest_price = lowest_price[:-1]
                lowest_price = str(lowest_price).replace(",", ".")
            else:
                response = self.RequestManager.getRequestAllAvailableProxies(
                    "https://steamcommunity.com/market/listings/730/"
                    + str(final_listing.full_item_name), False, "price"
                )
                if price_overview_page is None:
                    continue
                listing_source_page = response.text
                nameid_url = HelperFunctions.manuallyGetNameIDURL(
                    listing_source_page=listing_source_page
                )
                if nameid_url is None:
                    continue
                else:
                    alt_response = self.RequestManager.getRequestAllAvailableProxies(
                        nameid_url, False, "price"
                    )
                    if alt_response is None:
                        continue
                    alt_price_overview_json = json.loads(alt_response.text)
                    if len(str(alt_price_overview_json["lowest_sell_order"])) > 2:
                        lowest_price = str(
                            alt_price_overview_json["lowest_sell_order"]
                        )[:-2]

            lowest_price = str(lowest_price).replace(" ", "")
            lowest_price = str(lowest_price).replace("--", "0")

            try:
                if float(final_listing.price) <= float(lowest_price) * 5:
                    single_cheap_top_skin[str(final_listing.full_item_name)] = [
                        str(final_listing.rank),
                        str(final_listing.price),
                        str(final_listing.market_url),
                    ]
                    HelperFunctions.writeSingleCheapSkinToFile(single_cheap_top_skin)
                else:
                    if inspect_link != "" and rank == 1337:
                        try:
                            postgresql_conn = psycopg2.connect(
                                database="postgres",
                                user="postgres",
                                password="Berufsorientierung1!",
                                host="23.88.122.57",
                                port="6432",
                            )
                            postgresql_cur = postgresql_conn.cursor()
                            postgresql_cur.execute(
                                "INSERT INTO floats(inspect_link, rank) VALUES(%s, %s)",
                                (
                                    inspect_link,
                                    rank,
                                ),
                            )
                            postgresql_conn.commit()
                            postgresql_cur.close()
                        except (Exception, psycopg2.DatabaseError) as error:
                            logger.error(str(error))
                        finally:
                            if postgresql_conn is not None:
                                postgresql_conn.close()
            except ValueError:
                logger.critical("ValueError in singleCheckForPotentialBuy: " + str(e))
            end = True

    def testInspectLinks(self):
        self.high_low = "low"
        self.listings_url_set.add(
            "https://steamcommunity.com/market/listings/730/SCAR-20%20%7C%20Palm%20(Factory%20New)/render/?query="
        )
        self.buildInspectLinksList()
        self.getBestOrWorstSkinsBulk()

    def startBot(self):
        self.getHashedNameListHighOrLow()
        logger.info("1/2 Build Listing URLs finished (" + str(self.weapon_name) + ")")

        self.buildInspectLinksList()
        logger.info(
            "2/2 Build Inspect Links List finished (" + str(self.weapon_name) + ")"
        )

    def startBotSingleSkin(self, listings_url, greater_than, lower_than):
        self.listings_url_set.add(listings_url)
        self.extended_scrape = True
        self.buildInspectLinksList()
        logger.info(
            "2/3 SINGLE Build Inspect Links List finished ("
            + str(self.weapon_name)
            + ")"
        )

        self.getSkinsWithDefinedValue(greater_than, lower_than)
        logger.info("3/3 SINGLE Get top skins finished (" + str(self.weapon_name) + ")")

    def testFun(self, aids):
        logger.critical(aids)
