import sform

from django.db.models import Q

from staff.departments.models import Department

from ._base import lib, FieldFilter, BaseEqual, BaseIn, BaseInHierarchy


@lib.register
class DepartmentFilter(FieldFilter):
    """Подразедение, равно/в списке/в иерархии, саджест"""


class EqualForm(sform.SForm):
    department = sform.SuggestField(
        queryset=Department.objects.all(),
        label_fields='name',
        state=sform.REQUIRED,
    )


@DepartmentFilter.register
class InHierarchy(BaseInHierarchy):
    form_cls = EqualForm

    def q(self):
        dep = self.cleaned_data['department']
        return Q(
            department__tree_id=dep.tree_id,
            department__lft__gte=dep.lft,
            department__rght__lte=dep.rght,
        )


@DepartmentFilter.register
class InHierarchyExclude(InHierarchy):
    def q(self):
        return ~ super(InHierarchyExclude, self).q()


@DepartmentFilter.register
class Equal(BaseEqual):
    form_cls = EqualForm

    def q(self):
        return Q(department=self.cleaned_data['department'])


@DepartmentFilter.register
class Exclude(Equal):
    def q(self):
        return ~ super(Exclude, self).q()


class InForm(sform.SForm):
    departments = sform.MultipleSuggestField(
        queryset=Department.objects.filter(intranet_status=1),
        label_fields='name',
        state=sform.REQUIRED,
    )


# @DepartmentFilter.register
class In(BaseIn):
    form_cls = InForm

    def q(self):
        return Q(department__in=self.cleaned_data['departments'])
