# -*- coding: utf-8 -*-
from django.conf import settings

from events.common_app.directory import DirectorySuggest, BiSearchSuggest
from events.common_app.middleware import get_current_request
from events.data_sources.sources.base import (
    BaseDataSourceCategory,
    BaseDataSource,
    SimpleDataSourceSerializer,
)


class DirDataSourceCategory(BaseDataSourceCategory):
    name = 'dir'
    title = 'Коннект'


class DirItemDataSourceSerializer(SimpleDataSourceSerializer):
    id_attr = 'id'
    text_attr = 'title'

    class Meta:
        fields = ('id', 'title')


class DirBaseDataSource(BaseDataSource):
    category = DirDataSourceCategory()
    allow_external_usage = True
    is_need_auth = True
    is_for_external_site_type = True
    is_proxy_data_source = True
    is_with_pagination = True
    serializer_class = DirItemDataSourceSerializer
    connect_only = True
    layer = None

    @classmethod
    def get_view_class(cls):
        from events.data_sources.api.views import DataSourceBaseViewSet
        return DataSourceBaseViewSet

    def get_queryset(self):
        return None

    def get_filtered_queryset(self, filter_data=None):
        request = get_current_request()
        if not request.yauser.is_authenticated() or not request.orgs:
            return []

        org_dir_id = filter_data.get('dir_id') or request.orgs[0]
        if org_dir_id is None or org_dir_id not in request.orgs:
            return []

        _ids = filter_data.get('id', '')
        if isinstance(_ids, str):
            ids = [it for it in _ids.split(',') if it]
        else:
            ids = _ids
        text = filter_data.get('suggest', '')

        language = self.language
        if language not in ('ru', 'en'):
            language = None

        if settings.USE_BISEARCH:
            ds = BiSearchSuggest(request.user.uid, request.user.cloud_uid, org_dir_id, language)
        else:
            ds = DirectorySuggest(org_dir_id, language)
        result = ds.suggest(text=text, ids=ids, layers=[self.layer])
        return result[self.layer]['result']


class DirUserDataSource(DirBaseDataSource):
    name = 'dir_user'
    title = 'Пользователь'
    desc = 'Пользователь'
    layer = 'people'


class DirDepartmentDataSource(DirBaseDataSource):
    name = 'dir_department'
    title = 'Департамент'
    desc = 'Департамент'
    layer = 'departments'


class DirGroupDataSource(DirBaseDataSource):
    name = 'dir_group'
    title = 'Команда'
    desc = 'Команда'
    layer = 'groups'
