from django.db import models
from django.urls import reverse

from atlas.models import Subspecialty

# Create your models here.
class Entry(models.Model):
    modality = models.CharField(max_length=200)
    exam_code = models.CharField(max_length=50)
    exam_name = models.CharField(max_length=200)

    questions = models.TextField()

    questions_original = models.TextField()

    oef_name = models.CharField(max_length=200, blank=True)

    comments = models.TextField(blank=True)

    inactive = models.BooleanField(default=False)

    #format = models.ForeignKey('Formats', on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.exam_name

    def get_absolute_url(self):
        return reverse("oef:entry_detail", kwargs={"pk": self.pk})
    
    def clean(self) -> None:
        self.questions = self.questions.replace("\r\n", "\n")
        return super().clean()

    def save(self, *args, **kwargs):
        self.questions = self.questions.replace("\r\n", "\n")
        return super().save(*args, **kwargs)

    def get_current_format(self):
        return Formats.objects.filter(format=self.questions).first()

class Formats(models.Model):
    name = models.CharField(max_length=200)
    format = models.TextField(blank=True)

    inherits = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)

    specialties = models.ManyToManyField(Subspecialty, blank=True)

    def __str__(self):
        return self.name

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

    def clean(self) -> None:
        self.format = self.format.replace("\r\n", "\n")
        return super().clean()


    def save(self, *args, **kwargs):
        self.format = self.format.replace("\r\n", "\n")
        return super().save(*args, **kwargs)

    def get_format(self):
        formats = [self.format]
        while self.inherits:
            self = self.inherits
            formats.append(self.format)

        formats.reverse()
        return "\n".join(formats)

    def get_entries(self):
        return Entry.objects.filter(questions__icontains=self.get_format(), inactive=False)

    def get_entries_and_if_exact(self):
        entries = Entry.objects.filter(questions__icontains=self.get_format(), inactive=False)

        l = [(entry, entry.questions == self.get_format()) for entry in entries]

        return sorted(l, key=lambda x: (x[1], x[0].exam_code), reverse=False)
