from django.db.models import Q

from .base import PermQuery, PermManager, PermQueryBuilder


class VacancyPermQueryBuilder(PermQueryBuilder):
    """
    https://st.yandex-team.ru/FEMIDA-888
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        ls = lambda s: s.lstrip('__')

        self.vacancy_in_k = ls(self.prefix + '_id__in')
        self.is_hidden_k = ls(self.prefix + '__is_hidden')
        self.prof_sphere_k = ls(self.prefix + '__professional_sphere')

    def get_perm_q(self):
        if self.user.is_recruiting_manager:
            return None

        if self.user.is_recruiter or self.user.is_auditor:
            return self.not_hidden_vacancies_q | self.vacancies_membership_q

        return self.vacancies_membership_q

    @property
    def vacancies_membership_q(self):
        from intranet.femida.src.vacancies.models import VacancyMembership

        return Q(
            **{self.vacancy_in_k: (
                VacancyMembership.unsafe
                .filter(member=self.user)
                .values('vacancy')
            )}
        )

    @property
    def not_hidden_vacancies_q(self):
        return Q(**{self.is_hidden_k: False})


class VacancyPermQuery(PermQuery):
    _perm_query_builder_cls = VacancyPermQueryBuilder


class VacancyPermManager(PermManager):
    _perm_query_cls = VacancyPermQuery
