# coding: utf-8
from __future__ import unicode_literals

from staff.departments.models import DepartmentRoles
from staff.person.models import Staff


class AuthorIsChief(object):
    def __init__(self, author):
        self.author = author
        self._author_roles = None

    @property
    def author_roles(self):
        if self._author_roles is None:
            self._author_roles = (
                self.author.departmentstaff_set
                .filter(role_id=DepartmentRoles.CHIEF.value)
                .values(
                    'department__tree_id',
                    'department__rght',
                    'department__lft',
                )
            )

        return self._author_roles

    @classmethod
    def person_as_dict(cls, person):
        if isinstance(person, Staff):
            person = {
                'id': person.id,
                'department__tree_id': person.department.tree_id,
                'department__lft': person.department.lft,
                'department__rght': person.department.rght,
            }

        return person

    def __call__(self, person):
        person = self.person_as_dict(person)

        if person['id'] == self.author.id:
            return False

        for role in self.author_roles:
            is_chief = (
                role['department__tree_id'] == person['department__tree_id']
                and role['department__lft'] <= person['department__lft']
                and role['department__rght'] >= person['department__rght']
            )
            if is_chief:
                return True

        return False
