from logging import getLogger

from django.conf import settings

from intranet.search.core.query import parse_query, ParseError
from intranet.search.abovemeta import errors
from intranet.search.abovemeta.request import Request
from .base import CachedHttpStep


logger = getLogger(__name__)


class FemidaACLStep(CachedHttpStep):

    def get_cache_key(self, state):
        return f'femida_acl:{state.user}'

    def get_request(self, state):
        endpoint = settings.ISEARCH['api']['femida']['candidates_acl']

        query = {
            'login': state.user
        }
        if state.user_is_superuser and state.feature_value('replace_femida_acl_login'):
            # Даем возможность из админки смотреть выдачу для других логинов
            query['login'] = state.feature_value('replace_femida_acl_login')

        return Request(
            url=endpoint.url(query=query),
            headers=endpoint.headers(),
            type_='acl',
            name='femida_acl',
        )

    def set_data(self, state, data):
        if state.feature_enabled('ignore_femida_acl') and state.user_is_superuser:
            # Даем возможность из админки запросить все данные без ограничений
            return

        if data.get('allowed'):
            if not data.get('restrictions'):
                return

            try:
                state.acl_restrictions = parse_query(data.get('restrictions'), 5)
            except ParseError:
                logger.error('Cannot parse femida candidates restrictions',
                             extra={'restrictions': data.get('restrictions'), 'stack': True})
                state.set_error(errors.ERROR_ACL, 'Cannot parse restrictions for candidates search')
        else:
            state.set_error(errors.ERROR_ACL, 'You do not have permissions for candidates search')

    def set_error(self, state, response):
        state.set_error(errors.ERROR_ACL, 'Cannot get restrictions for candidates search')
