from django.core.management import call_command, get_commands
from django.conf import settings

from intranet.search.core import celery
from intranet.search.core.utils import lock


@celery.global_app.task(name='isearch.tasks.management')
def management(command, *args, **kwargs):
    commands = get_commands()

    _lock = kwargs.pop('_lock', False)
    _env = kwargs.pop('_env', None)
    lock_name = 'isearch:{}:{}'.format(commands[command], kwargs.pop('_lock_name', command))

    if _env and settings.YENV_TYPE not in _env:
        return

    if _lock:
        with lock.manager.lock(lock_name, block=False) as is_locked:
            if not is_locked:
                return

            call_command(command, *args, **kwargs)
    else:
        call_command(command, *args, **kwargs)
