<commit_before># -*- coding: utf-8 -*-

#
# Copyright (C) 2015-2019 <NAME> <<EMAIL>>
#

from qpanel import backend, config
from redis import Redis
from rq_scheduler import Scheduler
import datetime
import time
from rq import Connection, Worker


def check_connect_redis():
    try:
        Redis().echo("Check connection")
        return True
    except BaseException:
        return False


def reset_stats_queue(queuename, when, hour):
    '''
        Reset stat for a queue on backend
        queuename: Name of queue to reset
        when, hour parameters for more easy
               control for exists_job_onqueue
    '''
    remove_jobs_not_config()
    if not exists_job_onqueue(queuename, when, hour):
        return False
    b = backend.Backend()
    b.reset_stats(queuename)
    return True


def job_reset_stats_queue(queuename, when, hour):
    scheduler = Scheduler(connection=Redis())
    remove_jobs_not_config()
    if not exists_job_onqueue(queuename, when, hour):
        scheduler.schedule(
            scheduled_time=datetime_from_config(when, hour),
            func=reset_stats_queue,
            args=[queuename, when, hour],
            interval=seconds_from_config_interval(when)
        )


def exists_job_onqueue(queuename, when, hour):
    """
        Check if a job is present on queue
    """
    scheduler = Scheduler(connection=Redis())
    jobs = scheduler.get_jobs()
    for job in jobs:
        if 'reset_stats_queue' in job.func_name:
            args = job.args
            if queuename == args[0] and when == args[1] and hour == args[2]:
                return True
    return False


def remove_jobs_not_config():
    """
        Remove jobs on queue but not present on config.
        Prevent when in job for reset a queue stats is scheduled but
        after your config is modified or deleted
    """
    scheduler = Scheduler(connection=Redis())
    queue_for_reset = config.QPanelConfig().queues_for_reset_stats()
    jobs = scheduler.get_jobs()
    for job in jobs:
        if 'reset_stats_queue' in job.func_name:
            delete = True
            for qr in queue_for_reset:
                if qr in queue_for_reset:
                    if (queue_for_reset[qr]['when'] == job.args[1] and
                            queue_for_reset[qr]['hour'] == job.args[2]):
                        delete = False
                if delete:
                    job.delete()


def enqueue_reset_stats():
    queues_for_reset = config.QPanelConfig().queues_for_reset_stats()
    for queue, val in queues_for_reset.items():
        job_reset_stats_queue(queue, val['when'], val['hour'])


def get_days_from_val(val):
    val = val.lower()
    day = 0
    if val == 'daily':
        day = 1
    elif val in ['weekly', 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']:
        day = 7
    elif val == 'monthly':
        day = 30
    return day


def seconds_from_config_interval(val):
    """
        Get interval value for a configuration by parameter<commit_msg>Bugfix for remove_jobs_not_config<commit_after># -*- coding: utf-8 -*-

#
# Copyright (C) 2015-2019 <NAME> <<EMAIL>>
#

from qpanel import backend, config
from redis import Redis
from rq_scheduler import Scheduler
import datetime
import time
from rq import Connection, Worker


def check_connect_redis():
    try:
        Redis().echo("Check connection")
        return True
    except BaseException:
        return False


def reset_stats_queue(queuename, when, hour):
    '''
        Reset stat for a queue on backend
        queuename: Name of queue to reset
        when, hour parameters for more easy
               control for exists_job_onqueue
    '''
    remove_jobs_not_config()
    if not exists_job_onqueue(queuename, when, hour):
        return False
    b = backend.Backend()
    b.reset_stats(queuename)
    return True


def job_reset_stats_queue(queuename, when, hour):
    scheduler = Scheduler(connection=Redis())
    remove_jobs_not_config()
    if not exists_job_onqueue(queuename, when, hour):
        scheduler.schedule(
            scheduled_time=datetime_from_config(when, hour),
            func=reset_stats_queue,
            args=[queuename, when, hour],
            interval=seconds_from_config_interval(when)
        )


def exists_job_onqueue(queuename, when, hour):
    """
        Check if a job is present on queue
    """
    scheduler = Scheduler(connection=Redis())
    jobs = scheduler.get_jobs()
    for job in jobs:
        if 'reset_stats_queue' in job.func_name:
            args = job.args
            if queuename == args[0] and when == args[1] and hour == args[2]:
                return True
    return False


def remove_jobs_not_config():
    """
        Remove jobs on queue but not present on config.
        Prevent when in job for reset a queue stats is scheduled but
        after your config is modified or deleted

        TODO: Maybe this could reload by notified in config.ini change
    """
    scheduler = Scheduler(connection=Redis())
    queue_for_reset = config.QPanelConfig().queues_for_reset_stats()
    jobs = scheduler.get_jobs()
    for job in jobs:
        if 'reset_stats_queue' in job.func_name:
            delete = True
            for qr in queue_for_reset:
                # The args for the job of reset_stats_queue are:
                # args0 = queuename
                # args1 = type when
                # args2 = time hour to reset
                if qr == job.args[0]:
                    if (queue_for_reset[qr]['when'] == job.args[1] and  # noqa E504
                            queue_for_reset[qr]['hour'] == job.args[2]):
                        delete = False
            if delete:
                job.delete()


def enqueue_reset_stats():
    queues_for_reset = config.QPanelConfig().queues_for_reset_stats()
    for queue, val in queues_for_reset.items():
        job_reset_stats_queue(queue, val['when'], val['hour'])


def get_days_from_val(val):
    val = val.lower()
    day = 0
    if val == 'daily':
        day = 1
    elif val in ['weekly', 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']:
        day = 7
    elif val == 'monthly':
        day = 30
    return day


def seconds_from_config_interval(val):
    """
        Get interval value for a configuration by parameter
{'fraction_non_alphanumeric': 0.09443292391130961, 'fraction_numerical': 0.007178178337852927, 'mean_word_length': 2.3619302949061662, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1299446', 'n_tokens_mistral': 1920, 'n_tokens_neox': 1844, 'n_words': 544}