# coding: utf-8


import logging

from django.db.models import Q

from idm.api.frontend import forms
from idm.api.frontend.suggest.base import BaseSuggestResource
from idm.utils.i18n import get_localized_fieldname

logger = logging.getLogger(__name__)


class TvmSuggestResource(BaseSuggestResource):
    id_field_name = 'username'

    class Meta(BaseSuggestResource.Meta):
        resource_name = 'suggest/tvm/all'
        form = forms.SuggestForm

    def get_object_list(self, request, **kwargs):
        return request.user.get_managed_tvm_apps().order_by('first_name')

    def filter_objects(self, objects, request):
        objects = super(TvmSuggestResource, self).filter_objects(objects, request)
        if self.query['q']:
            objects = objects.filter(
                Q(username__startswith=self.query['q']) |
                Q(first_name__icontains=self.query['q'])
            )
        return objects

    def process_objects(self, objects, request):
        return [
            {
                'id': obj.username,
                'slug': obj.username,
                'name': f'{obj.first_name} ({obj.username})',
            }
            for obj in objects
        ]
