# coding: utf-8


from django.utils import timezone
from django.http import HttpResponse
from tastypie.authorization import Authorization

from idm.api.exceptions import BadRequest
from idm.api.frontend.base import FrontendApiResource
from idm.api.v1.base import RequesterMixin
from idm.core.models import Role


class StatusResource(RequesterMixin, FrontendApiResource):
    """
    Ручка, возвращающая произвольный код ответа
    """
    class Meta:
        object_class = None
        resource_name = 'status'
        allowed_methods = ('get',)
        authorization = Authorization()
        list_allowed_methods = []
        detail_allowed_methods = ['get']

    def get_detail(self, request, **kwargs):
        code = kwargs.get('pk')
        if code not in ('200', '400', '500'):
            code = '400'

        touch_role = request.GET.get('touch_role', None)
        if touch_role is not None:
            touch_role = int(touch_role)

        if touch_role and request.user.has_perm('core.rerequest_granted_role'):
            Role.objects.filter(pk=touch_role).update(updated=timezone.datetime.now())

        if code == '200':
            return HttpResponse('OK')
        elif code == '400':
            raise BadRequest()
        else:
            raise NotImplementedError()
