from django.db import models


class ApproveQuerySet(models.QuerySet):
    def approve(self):
        from idm.core.models import ApproveRequest

        self.update(approved=True)

        # В интерфейсе показываются только те ApproveRequest, у которых parent=None, поэтому тут надо перевыбрать
        new_parents_ids = []
        for approve_request in ApproveRequest.objects.filter(approve__in=self, children__isnull=False):
            active_requests = approve_request.children.filter(approve__approved=None)
            new_parent = active_requests.first()
            if new_parent is not None:
                active_requests.exclude(pk=new_parent.pk).update(parent=new_parent)
                new_parents_ids.append(new_parent.pk)

        ApproveRequest.objects.filter(pk__in=new_parents_ids).update(parent=None)

    def decline(self):
        self.update(approved=False)


class ApproveManager(models.Manager.from_queryset(ApproveQuerySet)):
    pass
