# Path: mrq/config.py
# def add_parser_args(parser, config_type):
#     def add_argument(self, *args, **kwargs):
# def get_config(
#         sources=(
#             "file",
#             "env"),
#         env_prefix="MRQ_",
#         file_path=None,
#         parser=None,
#         extra=None,
#         config_type=None):
#         def print_profiling():
# class ArgumentParserIgnoringDefaults(argparse.ArgumentParser):
# 
# Path: mrq/utils.py
# def normalize_command(command, worker_group):
# def get_local_ip():
# def group_iter(iterator, n=2):
# def memoize(f):
#         def __getitem__(self, *key):
#         def __missing__(self, key):
# def memoize_single_argument(f):
#         def __missing__(self, key):
# def load_class_by_path(taskpath):
# def lazyproperty(fn):
#     def _lazyprop(self):
# def wait_for_net_service(server, port, timeout=None, poll_interval=0.1):
#     def __init__(self):
#     def add_factory(self, factory):
#     def __getattr__(self, attr):
#     def reset(self):
#     def default(self, obj):  # pylint: disable=E0202
#     def __init__(self, size):
#     def next(self, val):
#     def __init__(self, size):
#     def next(self, val, t=None):
#         def std(lst, m):
#         def pearson_r(list_t, list_q):
#     class memodict(dict):
#     class memodict(dict):
# class LazyObject(object):
# class MongoJSONEncoder(json.JSONEncoder):
# class MovingAverage(object):
# class MovingETA(object):
# 
# Path: mrq/context.py
# _GLOBAL_CONTEXT = {
# 
#     # Contains all the running greenlets for this worker. greenletid => Job object
#     "greenlets": {},
# 
#     # pointer to the current worker
#     "worker": None,
# 
#     # pointer to the current config
#     "config": {}
# }
# def setup_context(**kwargs):
# def set_current_job(job):
# def get_current_job(greenlet_id=None):
# def set_current_worker(worker):
# def get_current_worker():
# def set_logger_config():
# def set_current_config(config):
# def get_current_config():
# def retry_current_job(delay=None, max_retries=None, queue=None):
# def abort_current_job():
# def _connections_factory(attr):
#     def versiontuple(v):
# def enable_greenlet_tracing():
#     def trace(*args):
# def run_task(path, params):
# def set_current_job_progress(ratio, save=False):
# def queue_raw_jobs(*args, **kwargs):
# def queue_job(*args, **kwargs):
# def queue_jobs(*args, **kwargs):
# def metric(*args, **kwargs):
# 
# Path: mrq/job.py
# def queue_job(main_task_path, params, **kwargs):
#     """ Queue one job on a regular queue """
# 
#     return queue_jobs(main_task_path, [params], **kwargs)[0]
# 
# Path: mrq/utils.py
# @memoize_single_argument
# def load_class_by_path(taskpath):
#     """ Given a taskpath, returns the main task class. """
# 
#     return getattr(
#         importlib.import_module(
#             re.sub(
#                 r"\.[^.]+$",
#                 "",
#                 taskpath)),
#         re.sub(
#             r"^.*\.",
#             "",
#             taskpath))
# 
# class MongoJSONEncoder(json.JSONEncoder):
# 
#     def default(self, obj):  # pylint: disable=E0202
#         if isinstance(obj, (datetime.datetime, datetime.date)):
#             return obj.isoformat()
#         elif isinstance(obj, ObjectId):
#             return str(obj)
#         elif isinstance(obj, uuid.UUID):
#             return str(obj)
#         elif isinstance(obj, bytes):
#             return obj.decode('utf-8')
#         return json.JSONEncoder.default(self, obj)


import os
import sys
import argparse
import ujson as json
import json as json_stdlib
import datetime
from gevent import monkey
from mrq import config, utils
from mrq.context import set_current_config, set_logger_config, set_current_job, connections
from mrq.job import queue_job
from mrq.utils import load_class_by_path, MongoJSONEncoder
# We must still monkey-patch the methods for job sub-pools.
monkey.patch_all()


sys.path.insert(0, os.getcwd())


def main():

    parser = argparse.ArgumentParser(description='Runs a task')

    cfg = config.get_config(parser=parser, config_type="run", sources=("file", "env", "args"))
    cfg["is_cli"] = True
    set_current_config(cfg)
    set_logger_config()

    if len(cfg["taskargs"]) == 1:
        params = json.loads(cfg["taskargs"][0])  # pylint: disable=no-member
    else:
        params = {}

        # mrq-run taskpath a 1 b 2 => {"a": "1", "b": "2"}
        for group in utils.group_iter(cfg["taskargs"], n=2):
            if len(group) != 2:
                print("Number of arguments wasn't even")
                sys.exit(1)
            params[group[0]] = group[1]

    if cfg["queue"]:
        ret = queue_job(cfg["taskpath"], params, queue=cfg["queue"])

# Path: mrq/config.py
# def add_parser_args(parser, config_type):
#     def add_argument(self, *args, **kwargs):
# def get_config(
#         sources=(
#             "file",
#             "env"),
#         env_prefix="MRQ_",
#         file_path=None,
#         parser=None,
#         extra=None,
#         config_type=None):
#         def print_profiling():
# class ArgumentParserIgnoringDefaults(argparse.ArgumentParser):
# 
# Path: mrq/utils.py
# def normalize_command(command, worker_group):
# def get_local_ip():
# def group_iter(iterator, n=2):
# def memoize(f):
#         def __getitem__(self, *key):
#         def __missing__(self, key):
# def memoize_single_argument(f):
#         def __missing__(self, key):
# def load_class_by_path(taskpath):
# def lazyproperty(fn):
#     def _lazyprop(self):
# def wait_for_net_service(server, port, timeout=None, poll_interval=0.1):
#     def __init__(self):
#     def add_factory(self, factory):
#     def __getattr__(self, attr):
#     def reset(self):
#     def default(self, obj):  # pylint: disable=E0202
#     def __init__(self, size):
#     def next(self, val):
#     def __init__(self, size):
#     def next(self, val, t=None):
#         def std(lst, m):
#         def pearson_r(list_t, list_q):
#     class memodict(dict):
#     class memodict(dict):
# class LazyObject(object):
# class MongoJSONEncoder(json.JSONEncoder):
# class MovingAverage(object):
# class MovingETA(object):
# 
# Path: mrq/context.py
# _GLOBAL_CONTEXT = {
# 
#     # Contains all the running greenlets for this worker. greenletid => Job object
#     "greenlets": {},
# 
#     # pointer to the current worker
#     "worker": None,
# 
#     # pointer to the current config
#     "config": {}
# }
# def setup_context(**kwargs):
# def set_current_job(job):
# def get_current_job(greenlet_id=None):
# def set_current_worker(worker):
# def get_current_worker():
# def set_logger_config():
# def set_current_config(config):
# def get_current_config():
# def retry_current_job(delay=None, max_retries=None, queue=None):
# def abort_current_job():
# def _connections_factory(attr):
#     def versiontuple(v):
# def enable_greenlet_tracing():
#     def trace(*args):
# def run_task(path, params):
# def set_current_job_progress(ratio, save=False):
# def queue_raw_jobs(*args, **kwargs):
# def queue_job(*args, **kwargs):
# def queue_jobs(*args, **kwargs):
# def metric(*args, **kwargs):
# 
# Path: mrq/job.py
# def queue_job(main_task_path, params, **kwargs):
#     """ Queue one job on a regular queue """
# 
#     return queue_jobs(main_task_path, [params], **kwargs)[0]
# 
# Path: mrq/utils.py
# @memoize_single_argument
# def load_class_by_path(taskpath):
#     """ Given a taskpath, returns the main task class. """
# 
#     return getattr(
#         importlib.import_module(
#             re.sub(
#                 r"\.[^.]+$",
#                 "",
#                 taskpath)),
#         re.sub(
#             r"^.*\.",
#             "",
#             taskpath))
# 
# class MongoJSONEncoder(json.JSONEncoder):
# 
#     def default(self, obj):  # pylint: disable=E0202
#         if isinstance(obj, (datetime.datetime, datetime.date)):
#             return obj.isoformat()
#         elif isinstance(obj, ObjectId):
#             return str(obj)
#         elif isinstance(obj, uuid.UUID):
#             return str(obj)
#         elif isinstance(obj, bytes):
#             return obj.decode('utf-8')
#         return json.JSONEncoder.default(self, obj)


# Path: mrq/bin/mrq_run.py
import os
import sys
import argparse
import ujson as json
import json as json_stdlib
import datetime
from gevent import monkey
from mrq import config, utils
from mrq.context import set_current_config, set_logger_config, set_current_job, connections
from mrq.job import queue_job
from mrq.utils import load_class_by_path, MongoJSONEncoder

# We must still monkey-patch the methods for job sub-pools.
monkey.patch_all()


sys.path.insert(0, os.getcwd())


def main():

    parser = argparse.ArgumentParser(description='Runs a task')

    cfg = config.get_config(parser=parser, config_type="run", sources=("file", "env", "args"))
    cfg["is_cli"] = True
    set_current_config(cfg)
    set_logger_config()

    if len(cfg["taskargs"]) == 1:
        params = json.loads(cfg["taskargs"][0])  # pylint: disable=no-member
    else:
        params = {}

        # mrq-run taskpath a 1 b 2 => {"a": "1", "b": "2"}
        for group in utils.group_iter(cfg["taskargs"], n=2):
            if len(group) != 2:
                print("Number of arguments wasn't even")
                sys.exit(1)
            params[group[0]] = group[1]

    if cfg["queue"]:
        ret = queue_job(cfg["taskpath"], params, queue=cfg["queue"])

        print(ret)