from django.conf import settings

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


class GroupPermissionsStep(CachedHttpStep):

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

    def get_request(self, state):
        endpoint = settings.ISEARCH['api']['staff']['departmentstaff']
        fields = [
            'department_group.id',
        ]
        query = {
            'person.login': state.user,
            '_fields': ','.join(fields),
        }
        return Request(
            url=endpoint.url(query=query),
            type_='staff',
            name='group_permissions',
            headers=endpoint.headers(),
            request_timeout=timeouts['groups'],
            retries=1,
        )

    def set_data(self, state, data):
        state.user_departments_access = [
            group['department_group']['id']
            for group in data['result']
            if group.get('department_group')
        ]
