# coding: utf-8


import logging

from idm.api.frontend.suggest.base import (
    SuggestTVMSwitchResource,
    BaseSubjectSuggestResource,
    ProxiedSuggestResource
)
from idm.users.constants.user import USER_TYPES
from idm.users.models import Subject

logger = logging.getLogger(__name__)


class ProxiedSubjectSuggestResource(ProxiedSuggestResource):

    class Meta(ProxiedSuggestResource.Meta):
        layer = 'idm_subjects'

    def process_object(self, obj):
        is_group = obj['fields']['object_type'] == 'groups'
        return {
            'department__name': obj['fields'].get('department_name'),
            'first_name': obj['fields'].get('first_name'),
            'full_name': obj['title'],
            'group_type': obj['fields'].get('type') if is_group else None,
            'id': obj['id'],
            'is_group': is_group,
            'last_name': obj['fields'].get('last_name'),
            'login': obj['fields'].get('slug') if is_group else obj['id'],
            'subject_type': obj['fields'].get('object_type')[:-1]  # убираем s
        }


class LocalSubjectSuggestResource(BaseSubjectSuggestResource):
    fullname_field = 'full_name'
    fullname_en_field = 'full_name_en'
    ident_sql = 'username'

    def filter_by_type(self, objects, type):
        if type == USER_TYPES.TVM_APP:
            objects = objects.filter(user__type=type)

        return objects

    def process_objects(self, objects, request):
        for obj in objects:
            self.process_object(obj, request)

        return [self.process_object(obj, request) for obj in objects]

    def process_object(self, obj, request):
        return {
            'id': obj.external_id,  # username для пользователей, external_id для групп
            'login': obj.username,
            'is_group': obj.is_group,
            'subject_type': obj.subject_type,
            'group_type': obj.group_type,
            'department__name': obj.parent_name,
            'first_name': obj.first_name,
            'last_name': obj.last_name,
            'full_name': obj.get_full_name(),
        }

    def get_object_list(self, request, **kwargs):
        return Subject.objects.order_by('is_group', 'first_name', 'last_name', 'full_name', 'username')


class SubjectSuggestSwitchResource(SuggestTVMSwitchResource):

    class Meta(SuggestTVMSwitchResource.Meta):
        resource_name = 'suggest/subjects/all'
        switch_options = {
            True: ProxiedSubjectSuggestResource,
            False: LocalSubjectSuggestResource
        }
