# coding: utf-8


import logging

from django import forms as django_forms
from django.db.models import Q

from idm.api.frontend import forms
from idm.api.frontend.suggest.base import BaseSuggestResource
from idm.core.models import RoleNodeSet

logger = logging.getLogger(__name__)


class BaseNodeSetSuggestResource(BaseSuggestResource):
    id_field = django_forms.CharField()
    id_field_name = 'set_id'

    def filter_objects(self, objects, request):
        objects = super(BaseNodeSetSuggestResource, self).filter_objects(objects, request)

        if self.query['q']:
            objects = objects.filter(
                Q(set_id__icontains=self.query['q']) |
                Q(name__icontains=self.query['q']) |
                Q(name_en__icontains=self.query['q'])
            )
        return objects

    def process_objects(self, objects, request):
        objects = list(set(objects))
        objects.sort(key=lambda nodeset: nodeset.set_id)
        result = [{
            'id': nodeset.set_id,
            'name': nodeset.get_name()
        } for nodeset in objects]
        return result


class AllNodeSetSuggestResource(BaseNodeSetSuggestResource):
    class Meta:
        object_class = None
        form = forms.SuggestByRequiredSystemForm
        resource_name = 'suggest/nodesets/all'

    def get_object_list(self, request, **kwargs):
        return RoleNodeSet.objects.active(system=self.query['system'])
