# coding: utf-8


import logging
import operator

from idm.api.frontend.forms import SuggestByRequiredSystemForm
from idm.api.frontend.suggest.base import BaseSuggestResource
from idm.core.constants.action import ACTION
from idm.core.constants.role import ROLE_STATE
from idm.core.constants.system import SYSTEM_AUTH_FACTOR
from idm.inconsistencies.models import Inconsistency
from idm.core.plugins.generic import HANDLE_CHOICES, LIBRARY_CHOICES
from idm.users.models import Group

logger = logging.getLogger(__name__)


class RawSuggestResource(BaseSuggestResource):
    def filter_objects(self, objects, request):
        if self.query['id']:
            objects = [
                record for record in objects
                if self.query['id'] == record['slug'].lower()
            ]
        if self.query['q']:
            objects = [
                record for record in objects
                if self.query['q'] in record['slug'].lower() or self.query['q'] in record['name'].lower()
            ]
        return objects


class ActionTypeSuggestResource(RawSuggestResource):
    """
        типы действий
    """
    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/actiontype'

    def get_object_list(self, request, **kwargs):
        return [
            {'id': slug, 'slug': slug, 'name': names[2]}
            for slug, names in sorted(ACTION.ACTIONS.items(), key=lambda item: item[1])
        ]


class ChoicesBasedSuggestResource(RawSuggestResource):
    order_key = None

    def get_object_list(self, request, **kwargs):
        return [
            {'id': slug, 'slug': slug, 'name': name}
            for slug, name in
            (sorted(self.choices, key=self.order_key) if self.order_key else self.choices)
        ]


class RoleStateSuggestResource(ChoicesBasedSuggestResource):
    """ статусы ролей """
    choices = list(ROLE_STATE.STATE_CHOICES.items())
    order_key = operator.itemgetter(1)

    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/rolestate'


class GroupTypeSuggestResource(ChoicesBasedSuggestResource):
    """ типы групп """
    choices = Group.GROUP_CHOICES
    order_key = operator.itemgetter(1)

    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/grouptype'


class HandleSuggestResource(ChoicesBasedSuggestResource):
    """ ручки систем """
    choices = HANDLE_CHOICES

    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/pluginhandle'


class AuthFactorSuggestResource(ChoicesBasedSuggestResource):
    """ использование сертификата """
    choices = SYSTEM_AUTH_FACTOR.CHOICES

    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/authfactor'
        form = SuggestByRequiredSystemForm

    def get_object_list(self, request, **kwargs):
        obj_list = super(AuthFactorSuggestResource, self).get_object_list(request)
        default_choice = self.query['system'].auth_factor
        for obj in obj_list:
            if obj['slug'] == default_choice:
                obj['default'] = True
        return obj_list


class LibrarySuggestResource(ChoicesBasedSuggestResource):
    """ типы групп """
    choices = LIBRARY_CHOICES

    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/pluginlibrary'


class InconsistencyStateSuggestResource(ChoicesBasedSuggestResource):
    """ статусы расхождений """

    choices = Inconsistency.STATE_CHOICES

    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/inconsistencystate'


class InconsistencyTypeSuggestResource(ChoicesBasedSuggestResource):
    """ типы расхождений """

    choices = Inconsistency.TYPES

    class Meta(RawSuggestResource.Meta):
        resource_name = 'suggest/raw/inconsistencytype'
