from staff.groups.models import Group

from staff.departments.controllers.group import DepartmentGroupCtl
from staff.departments.controllers.exceptions import DepartmentCtlError


def actualize_group(dep_ctl):
    group = dep_ctl.group  # todo: через контроллер группы
    group_ctl = DepartmentGroupCtl(group)
    group_ctl.parent = (
        dep_ctl.parent.group
        if dep_ctl.parent
        else Group.objects.get(url='__departments__')
    )
    group_ctl.name = dep_ctl.name
    group_ctl.save()


def validate_parent_is_not_child(dep_ctl, new_parent):
    if new_parent:
        if new_parent.is_descendant_of(dep_ctl.instance, include_self=True):
            raise DepartmentCtlError(
                'Cannot assign descendant or itself as parent',
                code='cannot_set_parent',
                params={
                    'dep_id': dep_ctl.instance.id,
                    'parent_id': new_parent.id,
                },
            )
