from datetime import datetime

from django.db import models

from staff.departments.models import Department, InstanceClass
from staff.lib.models.base import TrackableModel
from staff.person.models import Staff


class Umbrella(TrackableModel):
    goal_id = models.IntegerField(null=True, unique=True)
    issue_key = models.CharField(max_length=24, unique=True)
    name = models.CharField(max_length=128)
    value_stream = models.ForeignKey(
        Department,
        null=False,
        related_name='umbrellas',
        limit_choices_to={'instance_class': InstanceClass.VALUESTREAM.value},
    )


class UmbrellaAssignmentManager(models.Manager):
    def active(self):
        return super().filter(
            models.Q(engaged_to__isnull=True) | models.Q(engaged_to__gte=datetime.now()),
            intranet_status__gt=0,
        )


class UmbrellaAssignment(TrackableModel):
    person = models.ForeignKey(Staff, related_name='umbrellas')
    umbrella = models.ForeignKey(Umbrella, related_name='persons', null=True)
    engagement = models.DecimalField(max_digits=16, decimal_places=3)
    engaged_from = models.DateTimeField()
    engaged_to = models.DateTimeField(null=True)

    all_assignments: UmbrellaAssignmentManager = UmbrellaAssignmentManager()
