from logging import getLogger

from django.conf import settings
from django.utils.functional import cached_property

from intranet.search.core.sources.directory.client import TYPE_GROUP, TYPE_DEPARTMENT, DirectoryApiClient
from intranet.search.core.utils import format_directory_group
from intranet.search.core.utils.cache import CacheAdapter


log = getLogger(__name__)


# схема соответствия типа в стартреке типу группы в директории
TRACKER_GROUP_TYPE_MAP = {
    4: TYPE_GROUP,
    5: TYPE_DEPARTMENT,
}


class GroupsCache(CacheAdapter):
    """
    Кэш групп стартрека
    """
    def __init__(self, cache, api_client):
        self.api_client = api_client
        super().__init__(cache, 'tracker_groups')

    def get_default(self, short_key):
        return self.api_client.groups.get(short_key, externalId='true').as_dict()


class PeopleCache(CacheAdapter):
    """
    Кэш пользователей директории
    """
    def __init__(self, cache, organization_id):
        self.api_client = DirectoryApiClient()
        self.organization_id = organization_id
        super().__init__(cache, 'directory_people')

    def get_default(self, short_key):
        data = self.api_client.get_users(
            organization_id=self.organization_id,
            id=short_key,
            is_dismissed='ignore',
            fields='id,nickname,name',
        )
        if data['total'] == 1:
            return data['result'][0]
        else:
            log.error('Get ')
            return {'id': short_key}


class BisearchTrackerIndexerMixin:

    @cached_property
    def groups_cache(self):
        return GroupsCache(self.cache_storage, self.api_client)

    @cached_property
    def people_cache(self):
        return PeopleCache(self.cache_storage, self.revision['organization']['directory_id'])

    @cached_property
    def api_client(self):
        client = self._get_api_client()
        connection = client._connection
        connection.session.headers['X-Org-Id'] = str(self.revision['organization']['directory_id'])
        connection.session.verify = settings.ISEARCH_CA_CERTS
        return client

    def get_groups_permissions(self, permissions):
        result = []
        for group in permissions['groups']:
            data = self.groups_cache[group['id']]
            if not data:
                log.warning('Cannot get group data for group %s', group)
                continue
            result.append(format_directory_group({
                'type': TRACKER_GROUP_TYPE_MAP.get(data['type']),
                'id': data['externalId'],
            }))
        return result
