'''
Job scheduler, based on redis, rq and rq-schedule
'''
from redis import Redis
from rq import Queue
from rq_scheduler import Scheduler as RQ_Scheduler
from wf.Job import Job
from tf_py_utils.TF_WsService import TF_WsService

class Scheduler:

    redis_conn = None
    queue_name = None
    queue = None
    scheduler = None
    ws = None
    ready = False

    '''
    @:param ws an instance of TF_WsService to talk to Tachofresh
    @:param quque_name redis queue name to use for scheduler
    '''
    def __init__(self, ws, queue_name):
        try:
            self.ws = ws
            self.queue_name = queue_name
            self.redis_conn = Redis()
            self.queue = Queue(self.queue_name, connection=self.redis_conn)
            self.scheduler = RQ_Scheduler(queue=self.queue, connection=self.redis_conn) # looks like it needs the connection also even if Queue specified
            self.ready = True
        except Exception as err:
            self.ready = False;
            print(err)

    def schedule_job(self, job):
        if not self.ready:
            return False

        self.scheduler.enqueue_at(job.time, job.func, job.kwargs)
        return True

    def remove_job(self, job_id):
        if not self.ready:
            return False
        return True

    def list_jobs(self):
        if not self.ready:
            return False
        return self.scheduler.get_jobs()