import functools
import logging
import threading
import pika
from pika.exchange_type import ExchangeType
import json
from FindWeapon import findWeapon
from FindSkin import findSkin
from RequestManager import RequestManager
import os



LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
              '-35s %(lineno) -5d: %(message)s')
LOGGER = logging.getLogger(__name__)

logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

ReqManager = RequestManager()
ReqManager.createAWSGateways()

def ack_message(ch, delivery_tag):
    """Note that `ch` must be the same pika channel instance via which
    the message being ACKed was retrieved (AMQP protocol constraint).
    """
    if ch.is_open:
        ch.basic_ack(delivery_tag)
        print("Done")
    else:
        # Channel is already closed, so we can't ACK this message;
        # log and/or do something that makes sense for your app in this case.
        pass


def do_work(ch, delivery_tag, body):
    thread_id = threading.get_ident()
    LOGGER.info('Thread id: %s Delivery tag: %s Message body: %s', thread_id,
                delivery_tag, body)

    result = body.decode()
    b = str(result).split("'question1'")
    if "'price': 6969" in b[1]:
        swagb = b[0] + "'price': 6969," + "'question1': ['Item 2']}]"
    else:
        swagb = b[0] + "'question1': ['Item 2']}]"
    result_json = json.loads(str(swagb.replace("'", '"')))[0]

    steamid = str(result).split(", ")[-2][1:-1]
    queryid = str(result).split(", ")[-1][:-1]
    print(result_json)

    if result_json["skin_or_weapon"] == "skin":
        while True:
            try:
                findSkin(result_json=result_json, steamid=steamid, queryid=queryid, ReqManager=ReqManager)
                break
            except Exception as e:
                print(str(e))

    if result_json["skin_or_weapon"] == "weapon":
        while True:
            try:
                findWeapon(result_json=result_json, steamid=steamid, queryid=queryid, ReqManager=ReqManager)
                break
            except Exception as e:
                print(str(e))
    
    
    directory = '/var/www/premiumrankchecker/rank_txts/'  # Replace with the specific directory path
    prefix = str(queryid) + "_" + str(steamid)  # Replace with the specific prefix to delete

    # Get all files in the directory
    files = os.listdir(directory)

    # Iterate over the files and delete those with the specific prefix
    for file in files:
        if file.startswith(prefix):
            file_path = os.path.join(directory, file)
            os.remove(file_path)
    
    cb = functools.partial(ack_message, ch, delivery_tag)
    ch.connection.add_callback_threadsafe(cb)


def on_message(ch, method_frame, _header_frame, body, args):
    thrds = args
    delivery_tag = method_frame.delivery_tag
    t = threading.Thread(target=do_work, args=(ch, delivery_tag, body))
    t.start()
    thrds.append(t)


credentials = pika.PlainCredentials('worker', 'Margarethe1!')
parameters = pika.ConnectionParameters(
    '23.88.122.57', credentials=credentials, heartbeat=5)
connection = pika.BlockingConnection(parameters)

channel = connection.channel()
channel.exchange_declare(
    exchange="task_queue",
    exchange_type=ExchangeType.direct,
    passive=False,
    durable=True,
    auto_delete=False)
channel.queue_declare(queue="task_queue", auto_delete=False, durable=True)
channel.queue_bind(
    queue="task_queue", exchange="task_queue", routing_key="task_queue")

channel.basic_qos(prefetch_count=5)

threads = []
on_message_callback = functools.partial(on_message, args=(threads))
channel.basic_consume('task_queue', on_message_callback)

try:
    channel.start_consuming()
except KeyboardInterrupt:
    channel.stop_consuming()

# Wait for all to complete
for thread in threads:
    thread.join()

connection.close()
