from intranet.search.abovemeta import errors
from intranet.search.abovemeta.request import Request
from intranet.search.abovemeta.steps.base import timeouts, CachedHttpStep, api_urls


class PermissionsStep(CachedHttpStep):

    def get_cache_key(self, state):
        return 'permissions:%s' % state.user

    def get_request(self, state):
        endpoint = api_urls['permissions']

        return Request(
            url=endpoint.url(query={'user': state.user}),
            type_='api',
            name='permissions',
            headers=endpoint.headers(),
            request_timeout=timeouts['permissions'],
        )

    def set_data(self, state, data):
        permissions = data['suggest'] if state.scope == 'suggest' else data['search']
        state.apply_user_permissions(data['common'])
        state.apply_search_permissions(permissions)

        for scope in data['search']:
            state.features['has_%s_access' % scope] = True

        state.features['has_full_search_access'] = (
            state.feature_enabled('has_search_access')
            and state.feature_enabled('has_wikisearch_access')
            and state.feature_enabled('has_docsearch_access')
            and state.feature_enabled('has_atsearch_access')
        )

    def set_error(self, state, response=None):
        state.set_error(errors.ERROR_ACL, 'Cannot get user permissions')
