import functools

from django.db import models

from ichec_django_core.models import (
    Member,
    TimesStampMixin,
    PopulatedForm,
    content_file_name,
)

from marinerg_facility.models import Facility

from .access_call import AccessCall


class AccessApplication(TimesStampMixin):

    class Meta:
        verbose_name = "Access Application"
        verbose_name_plural = "Access Application"

    class Status(models.TextChoices):
        CREATED = "CREATED", "Created"
        SUBMITTED = "SUBMITTED", "Submitted"
        AWAITING_FACILITY_REVIEW = "FACILITY", "Awaiting Facility Review"
        AWAITING_BOARD_REVIEW = "BOARD", "Awaiting Board Review"
        AWAITING_DECISION = "DECISION", "Awaiting Decision"
        ACCEPTED = "ACCEPTED", "Accepted"
        REJECTED = "REJECTED", "Rejected"

    facilities = models.ManyToManyField(
        Facility, related_name="application_choices", blank=True
    )

    reviewers = models.ManyToManyField(
        Member, related_name="applications_for_review", blank=True
    )

    chosen_facility = models.ForeignKey(
        Facility, on_delete=models.CASCADE, related_name="applications", null=True
    )

    request_start_date = models.DateTimeField(null=True)
    request_end_date = models.DateTimeField(null=True)
    dates_flexible = models.BooleanField(default=False)

    applicant = models.ForeignKey(Member, on_delete=models.CASCADE)
    call = models.ForeignKey(
        AccessCall, on_delete=models.CASCADE, related_name="applications"
    )

    summary = models.FileField(
        null=True,
        upload_to=functools.partial(content_file_name, "application_summary"),
    )
    status = models.CharField(
        max_length=10, choices=Status.choices, default=Status.CREATED
    )

    form = models.OneToOneField(PopulatedForm, on_delete=models.CASCADE)

    submitted = models.DateTimeField(null=True)

    def get_roles(self, user) -> list[str]:

        roles = []

        if self.call.coordinator.id == user.id:
            roles.append("coordinator")

        if self.call.board_chair.id == user.id:
            roles.append("chair")

        if self.applicant.id == user.id:
            roles.append("applicant")

        for member in self.reviewers.all():
            if member.id == user.id:
                roles.append("reviewer")
        return roles

    def __str__(self):
        return f"{self.applicant.email} application for '{self.call.title}'"
