import logging

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


logger = logging.getLogger(__name__)


class UserMetaStep(CachedHttpStep):

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

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

    def set_data(self, state, data):
        state.user_frequently_searched_people = list(data.get('frequently_searched_people', {}))
        state.user_recently_searched_people = list(data.get('recently_searched_people', {}))

    def set_error(self, state, response=None):
        logger.warning('Cannot get user meta for %s', state.user, extra={'state': state})
