from django.db import models

from ichec_django_core.models import Member, TimesStampMixin

from marinerg_facility.models import Facility

from .application import AccessApplication


class AccessApplicationFacilityReview(TimesStampMixin):

    confirmed_preapplication_discussion = models.BooleanField(default=False)
    confirmed_app_info_in_line_with_discussion = models.BooleanField(default=False)
    supporting_comments = models.TextField(blank=True)
    supporting_documents = models.FileField(null=True)
    facility = models.ForeignKey(Facility, on_delete=models.CASCADE)
    application = models.ForeignKey(AccessApplication, on_delete=models.CASCADE)


class AccessApplicationBoardReview(TimesStampMixin):
    class Decision(models.TextChoices):
        ACCEPT = "1", "ACCEPT"
        REJECT = "2", "REJECT"
        DECLINE = "3", "DECLINE"

    decision = models.CharField(max_length=10, choices=Decision.choices)
    comments = models.TextField(blank=True)
    application = models.ForeignKey(
        AccessApplication,
        on_delete=models.CASCADE,
        null=True,
        related_name="board_reviews",
    )
    reviewer = models.ForeignKey(Member, on_delete=models.CASCADE)
    supporting_document = models.FileField(null=True)

    @property
    def reviews_completed(self) -> bool:

        if self.application.call.require_all_reviews:
            return len(self.application.call.board_members.all()) == len(
                self.application.board_reviews.all()
            )
        else:
            return True

    def save(self, force_insert=False, force_update=False, *args, **kwargs):

        super().save(force_insert, force_update, *args, **kwargs)

        if self.reviews_completed:
            self.application.status = "DECISION"
            self.application.save()


class AccessApplicationBoardDecision(TimesStampMixin):
    class Decision(models.TextChoices):
        ACCEPT = "1", "ACCEPT"
        REJECT = "2", "REJECT"

    decision = models.CharField(max_length=10, choices=Decision.choices)
    comments = models.TextField(blank=True)
    application = models.ForeignKey(
        AccessApplication, on_delete=models.CASCADE, null=True
    )
    reviewer = models.ForeignKey(Member, on_delete=models.CASCADE)
    supporting_document = models.FileField(null=True)
    selected_facility = models.ForeignKey(
        Facility, on_delete=models.SET_NULL, null=True
    )

    def save(self, force_insert=False, force_update=False, *args, **kwargs):

        if self.decision == "1":
            self.application.status = "ACCEPTED"
        else:
            self.application.status = "REJECTED"
        if self.selected_facility and not self.application.chosen_facility:
            self.application.chosen_facility = self.selected_facility
        self.application.save()

        super().save(force_insert, force_update, *args, **kwargs)
