# coding: utf-8


from django.shortcuts import _get_queryset

from idm.framework.task import UnrecoverableError, DelayingError

__all__ = ('get_object_or_fail_task', 'get_object_or_retry_task')


def get_object_or_fail_task(klass, *args, **kwargs):
    return _get_object_or_raise(klass, UnrecoverableError, *args, **kwargs)


def get_object_or_retry_task(klass, *args, **kwargs):
    return _get_object_or_raise(klass, DelayingError, *args, **kwargs)


def _get_object_or_raise(klass, exception_klass, *args, **kwargs):
    queryset = _get_queryset(klass)
    try:
        result = queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        raise exception_klass('No %s matches the given query.' % queryset.model._meta.object_name)
    return result
