from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
import reversion
from django.utils.safestring import mark_safe

from atlas.models import Condition

# Create your models here.

@reversion.register()
class Item(models.Model):
    class LevelChoices(models.TextChoices):
        NONE = "", _("None")
        PART_1 = "P1", _("FRCR Part 1")
        PART_2 = "P2", _("FRCR Part 2")
        POST_GEN = "GEN", _("Post FRCR Generalist")
        POST_SPEC = "SPEC", _("Post FRCR Specialist")

    SPECIALTY_CHOICES = (
        ("Radiology", "Radiology"),
        ("Oncology", "Oncology"),
        ("Cross-faculty", "Cross-faculty"),
    )


    name = models.CharField(max_length=200, blank=True, default="")
    description = models.TextField(blank=True, default="")
    content_type = models.CharField(max_length=200, blank=True, default="")
    created_on = models.DateTimeField(null=True, blank=True)
    number_of_items = models.IntegerField(null=True, blank=True)
    specialty = models.CharField(max_length=50,blank=True, default="")
    access_count = models.IntegerField(null=True, blank=True)
    targeted_to_group = models.CharField(max_length=255, default="Targeted", blank=True)
    review_link = models.CharField(max_length=255, blank=True, default="")
    review_link_password = models.CharField(max_length=255, blank=True, default="")


    rcr_platform_id = models.CharField(max_length=255, unique=True)

    #radiology_category = models.ForeignKey("RadiologyCategory", on_delete=models.SET_NULL, null=True, blank=True, related_name="item_radiology")
    radiology_categories =  models.ManyToManyField("RadiologyCategory", blank=True, related_name="items_radiology")
    oncology_category = models.ForeignKey("OncologyCategory", on_delete=models.SET_NULL, null=True, blank=True, related_name="item_oncology")

    level = models.ManyToManyField("Level", blank=True)

    assessed_date = models.DateTimeField(auto_now=True)

    assessed_by = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="assessed_items")

    assigned_to_radiology = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, related_name="assigned_items_radiology")
    assigned_to_oncology = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, related_name="assigned_items_oncology")

    outcome = models.ForeignKey("Outcome", on_delete=models.SET_NULL, blank=True, null=True)
    outcome_reason = models.ForeignKey("OutcomeReason", on_delete=models.SET_NULL, blank=True, null=True)
    outcome_free_text = models.CharField(max_length=255, help_text="Reason for outcome (if not available above)", default="", blank=True)


    comments = models.TextField(blank=True)
    needs_review = models.BooleanField(default=False, help_text="Check if this item needs review.")

    completed_radiology = models.BooleanField(default=False)
    completed_oncology = models.BooleanField(default=False)

    radiology_condition = models.ManyToManyField(Condition, blank=True, related_name="rcr_migration_item")

    class Meta:
        ordering = ("pk",)

    def __str__(self):
        completed = ""
        if self.completed_oncology:
            completed = " [Completed ONC]"
        if self.completed_radiology:
            completed = completed + " [Completed RAD]"

        return f"{self.specialty} / {self.content_type} / {self.name}{completed}"

    def get_absolute_url(self):
        return reverse("rcr:radiology_detail_view", kwargs={"pk": self.pk})

    def get_assessed_by(self):
        assessors = self.assessed_by.all()
        if assessors:
            print (assessors)
            try:
                return ",".join([f"<span title='Assessed by {i.first_name} {i.last_name}'>{i.first_name[0]}{i.last_name[0]}</span>" for i in assessors])
            except IndexError:
                return ",".join([f"<span title='Assessed by {i.email}'>{i.email[:2]}</span>" for i in assessors])
        else:
            return ""

    def get_assessed_by_name(self):
        assessors = self.assessed_by.all()
        if assessors:
            try:
                return ", ".join([f"<span title='Assessed by {i.first_name} {i.last_name}'>{i.first_name} {i.last_name}</span>" for i in assessors])
            except IndexError:
                return ", ".join([f"<span title='Assessed by {i.email}'>{i.email[:2]}</span>" for i in assessors])
        else:
            return ""
    
    def get_level(self):
        return ", ".join([l.name for l in self.level.all()])

    def get_radiology_categories(self):
        return ", ".join([l.name for l in self.radiology_categories.all()])
    
    def get_radiology_condition(self):
        return ", ".join([l.name for l in self.radiology_condition.all()])
    def get_radiology_condition_line_breaks(self):
        return mark_safe("<br/>".join([l.name for l in self.radiology_condition.all()]))


class RadiologyCategory(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class OncologyCategory(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Level(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Outcome(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class OutcomeReason(models.Model):
    reason = models.CharField(max_length=255)

    def __str__(self):
        return self.reason