import logging

from django.conf import settings

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

log = logging.getLogger(__name__)


class RevisionsStep(HttpStep):
    def get_request(self, state):
        endpoint = api_urls['revisions']
        query = {
            'user': state.user_identifier,
            'groups': state.groups if settings.APP_NAME != 'bisearch' else [],  # ISEARCH-4771
            'request_id': state.request_id,
            'json': True,
        }
        if state.org_directory_id:
            # для b2b поиска организация находится в стейте,
            # для яндекса - автоматически возьмется из настроек при построении урла
            query['organization'] = state.org_directory_id
        if state.features:
            query.update({f'feature.{k}': v for k, v in state.features.items()})

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

    def set_data(self, state, parsed):
        revisions = {(r['search'], r['index'] or '', r['backend']): r for r in parsed}
        state.revisions = revisions

    def set_error(self, state, response):
        msg = 'No revisions found'
        if response is not None:
            msg += ', url %s' % response.request.url

        log.error(msg, extra={'state': state})
        state.set_error(errors.ERROR_REVISIONS, msg)
