from typing import Optional
import config
import redis  # dependency via rq
from rq import Queue

REDIS_QUEUE = Queue(connection=redis.Redis(host=config.REDIS_HOST, port=config.REDIS_PORT))
# _RQ_STATES = ['queued', 'started', 'deferred', 'finished', 'stopped', 'scheduled', 'canceled', 'failed']


def rq_job_status(job_id: str) -> Optional[str]:
    if config.RQ_DISABLED:
        return None

    rq_job = REDIS_QUEUE.fetch_job(job_id)
    status = rq_job.get_status(refresh=True) if rq_job else None
    return status


def rq_job_exists(job_id: str) -> bool:
    return rq_job_status(job_id) is not None


def rq_job_finalized(job_id: str) -> bool:
    answer = rq_job_exists(job_id) is False or rq_job_status(job_id) in ['finished', 'stopped', 'canceled', 'failed']
    return answer


def rq_job_failed(job_id: str):
    return rq_job_status(job_id) == 'failed'
