from intranet.search.abovemeta.request import Request

from .base import HttpStep, ParallelStep, api_urls, timeouts


class GroupAttrs(HttpStep):
    def __init__(self, search, revision, *args, **kwargs):
        self.search = search
        self.revision = revision
        super().__init__(*args, **kwargs)

    def get_request(self, state):
        attr_names = {i['name'] for i in self.search['group_attrs'].values()}

        if len(attr_names) > 1:
            raise ValueError('More than 1 grouping for search found, search : %s, attrs% %s',
                             self.search['name'], attr_names)

        query = {
            'revision': self.revision,
            'language': state.language,
            'user': state.user,
            'values': list(self.search['group_attrs']),
            'name': attr_names.pop(),
            'request_id': state.request_id,
        }

        endpoint = api_urls['group_attrs']

        return Request(
            url=endpoint.url(query=query),
            type_='api',
            name='group_attrs',
            headers=endpoint.get('headers', {}),
            request_timeout=timeouts['labels'],
        )

    def set_data(self, state, data):
        state.searches[self.search['name']]['group_attrs'].update(data)


class FullGroupAttrs(ParallelStep):
    def get_steps(self, state=None):
        steps = []
        for name, search in state.searches.items():
            if search.get('group_attrs'):
                for revision in search['search_settings']['revisions']:
                    steps.append(GroupAttrs(search, revision['id']))

        return steps
