import logging
import threading
import json
import time
from queue import Queue, Empty
from flask import Flask, jsonify, request
from waitress import serve

HOST_ADDRESS = "192.168.1.191"
PORT_ADDRESS = 5000
OUT_COMM_Q = Queue()
IN_COMM_Q = Queue()
awaiting_q = []
incoming_q = Queue()
app = Flask(__name__)
class QueryControl:
    """
    This class `QueryControl` is used to manage queries with information about the author, UUID,
    content, logger, context, and replies.
    """
    def __init__(self, query_author, query_uuid, query_content, uplogger, ctx) -> None:
        self.author = query_author
        self.uuid = query_uuid
        self.content = query_content
        self.logger = uplogger
        self.stop = False
        self.ctx = ctx
        self.logger.info(
            f"Created Query control for {self.author}, {self.uuid}: {self.content}"
        )
        self.replies = []

@app.route("/conjurer", methods=["POST"])
def answer_external_command():
    """
    The function `answer_external_command` logs the request data, loads the data as JSON, logs the
    record, and then puts the record into an incoming queue before returning a success message.
    :return: The function `answer_external_command()` is returning a JSON response with the message
    "SUCCESS".
    """
    app.logger.info(request)
    record = json.loads(request.data)
    app.logger.info(record)
    app.logger.info("DATA RECEIVED")
    incoming_q.put(record)
    return jsonify("SUCCESS")

@app.route("/conjurer", methods=["GET"])
def check_alive():
    """
    The function "check_alive" returns a JSON response with the message "ALIVE" when the "/conjurer"
    route is accessed via a GET request.
    :return: The code snippet is a Flask route that listens for GET requests to the "/conjurer"
    endpoint. When a GET request is made to this endpoint, the function check_alive() is called, which
    returns a JSON response with the message "ALIVE".
    """
    return jsonify("ALIVE")

def flask_debug(_logger):
    """
    The `flask_debug` function starts a Flask application in debug mode without using the reloader.
    Do not use for production for fucks sake.
    """
    _logger.info("Attempt debug")
    # trunk-ignore(bandit/B201)
    app.run(debug=True, use_reloader=False, host=HOST_ADDRESS, port=PORT_ADDRESS)


def waitress_run(_logger):
    """
    The `waitress_run` function serves the `app` on host "0.0.0.0"
    and port 5000 using the Waitress WSGI server.
    """
    _logger.info("Attempt waitress")
    serve(app, host=HOST_ADDRESS, port=PORT_ADDRESS)

def scan_queue(_logger):
    """
    The function `scan_queue` reads data from a queue, logs it, and appends it to another queue.

    :param _logger: The `_logger` parameter is typically an instance of a logging object that is used to
    record and store log messages. It is commonly used to track the flow of the program, record errors,
    and provide information for debugging purposes. In this code snippet, the `_logger` object is used
    to log the
    """
    while True:
        data = OUT_COMM_Q.get()
        _logger.info(data)
        awaiting_q.append(data)

def scan_incoming(_logger):
    """
    The `scan_incoming` function continuously checks for incoming data, processes it, and logs when data
    is found.

    :param _logger: The `_logger` parameter in the `scan_incoming` function is a logger object that is
    used to log messages or information during the execution of the function. It is typically used for
    debugging, monitoring, or tracking the flow of the program. In this case, the `_logger` is being
    used
    """
    while True:
        try:
            answer = incoming_q.get(block=False)
            _logger.info("DATA FOUND")
            record_stored = False
            for record in awaiting_q:
                if record.uuid in answer.keys():
                    record_stored = True
                    record.stop = True
                    record.entries = answer[record.uuid]
                    IN_COMM_Q.put(record)
            if not record_stored:
                for key in answer.keys():
                    record = QueryControl("Orphaned", key, "Orphan", _logger, None)
                    record.stop = True
                    record.entries = answer[record.uuid]
                    IN_COMM_Q.put(record)
        except Empty:
            time.sleep(1)


def comm_subroutine(logger):
    """
    The `comm_subroutine` function starts multiple threads to run different tasks concurrently.

    :param logger: The `logger` parameter in the `comm_subroutine` function is an instance of a logger
    object that is used for logging messages at various levels (e.g., debug, info, warning, error). In
    the provided code snippet, the logger is used to log messages at the "info" level
    """
    #logger.setLevel(logging.DEBUG)
    logger.info("Started")
    threads = []
    #threads.append(threading.Thread(target=flask_debug, args=(logger,)))
    threads.append(threading.Thread(target=waitress_run, args=(logger,)))
    threads.append(threading.Thread(target=scan_queue,args=(logger,)))
    threads.append(threading.Thread(target=scan_incoming,args=(logger,)))


    for worker in threads:
        worker.start()
    for worker in threads:
        worker.join()

if __name__ == "__main__":
    logging_client = logging.getLogger(__name__)
    comm_subroutine(logging_client)
