from .django_json import Django13JSONEncoder

from django.db.models import Q

from staff.person.models import Staff


class BaseCenterView(object):

    def __call__(self, request):
        self.request = request

    def _serialize_qs(self, qs, fields=None):
        res = []
        for item in qs:
            res.append(self._filter_model(item, fields))
        return Django13JSONEncoder().encode(res)

    def _filter_model(self, model, fields=None):
        fields = self._get_fields(fields)
        if fields:
            model_dict = model.__dict__
            r = {}
            for field in fields:
                r[field] = model_dict.get(field, None)
            return r
        else:
            r = model.__dict__
        for field in r.keys():
            if field and field[0] == '_':
                del r[field]
        return r

    def _get_fields(self, fields=None):
        if not fields:
            fields = self.request.GET.get('fields', self.request.POST.get('fields', ()))
        if fields and type(fields) == str:
            fields = fields.split('|')
        return fields


class UserView(BaseCenterView):
    @staticmethod
    def get_qs(login):
        emails = []
        logins = []
        ids = []
        values = login.split("|")
        for value in values:
            if value.find("@") != -1:
                emails.append(value)
            else:
                try:
                    ids.append(int(value))
                except ValueError:
                    logins.append(value)

        return Staff.objects.filter(Q(work_email__in=emails) | Q(login__in=logins) | Q(pk__in=ids))
