import logging
import threading
from typing import List

logger = logging.getLogger(__name__)


class Queue:
    "A queue for handling jobs"

    def __init__(self) -> None:
        self.jobs: List[str] = []
        self.lock = threading.Lock()
        self.condition = threading.Condition(self.lock)
        self.concurrent_jobs = 1  # Broken, do not change (torch becomes locked up)

    def mark_finished(self, job_id: str):
        "Mark the current job as finished"

        with self.lock:
            try:
                self.jobs.remove(job_id)
            except ValueError:
                logger.warning(
                    f"Job {job_id} was not in the queue, assuming queue was cleared manually by 3rd party"
                )

            self.condition.notify_all()
            logger.info(f"Job {job_id} has been processed")

    def wait_for_turn(self, job_id: str):
        "Wait until the job can be processed"

        with self.lock:
            self.jobs.append(job_id)

            while job_id not in self.jobs[: self.concurrent_jobs]:
                self.condition.wait()

            logger.info(f"Job {job_id} is now being processed")
            return

    def clear(self):
        "Clear the queue"

        self.jobs = []
        logger.info("Queue has been cleared")

    def trigger_condition(self):
        "Trigger the condition manually, this will cause all jobs to check if they can be processed"

        with self.lock:
            self.condition.notify_all()
            logger.info("Queue Condition has been triggered manually")
