from django.db import models
from django.contrib.auth.models import User
from datetime import date

from django.forms import ModelForm
from django import forms

# Create your models here.
class Genre(models.Model):
    """Model representing a book genre."""
    name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)')

    def __str__(self):
        """String for representing the Model object."""
        return self.name

# Create your models here.
class Type_Of_Injury(models.Model):
    """Model representing a book genre."""
    name = models.CharField(max_length=200, help_text='Enter a type of injury (e.g. Break, Burn)')

    def __str__(self):
        """String for representing the Model object."""
        return self.name
        
from django.urls import reverse # Used to generate URLs by reversing the URL patterns

class Language(models.Model):
    """Model representing a Language (e.g. English, French, Japanese, etc.)"""
    name = models.CharField(max_length=200,
                            help_text="Enter the book's natural language (e.g. English, French, Japanese etc.)")

    def __str__(self):
        """String for representing the Model object (in Admin site etc.)"""
        return self.name
        
from django.contrib.auth.models import User  # Required to assign User as a borrower
from catalog.choices import *


class BleedInfo(models.Model):
    """Model representing a book (but not a specific copy of a book)."""
    title = models.CharField(max_length=200)
    patient = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    ticket_initated_by = models.IntegerField(choices=USER_TYPES, default=1)
    when_bleed_occured = models.DateField()
    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the bleed')
    bleed_type = models.IntegerField(choices=BLEED_TYPE, default=1)
    bleed_location = models.IntegerField(choices=BODY_LOCATIONS, default=1)
    bleed_location_details = models.CharField(max_length=200)
    extra_factor_yn = models.IntegerField(choices=YES_NO, default=1)
    num_of_days_extra_factor_was_used =  models.IntegerField()
    name_of_extra_factor_drug = models.CharField(max_length=200)
    did_patient_use_factor_yn = models.IntegerField(choices=YES_NO, default=1)
    why_patinet_did_not_use_facor = models.CharField(max_length=200)
    did_patient_use_home_factor_yn = models.IntegerField(choices=YES_NO, default=1)
    home_factor_supply_details= models.CharField(max_length=200)

    def __str__(self):
        """String for representing the Model object."""
        return self.title

    def get_absolute_url(self):
        """Returns the url to access a detail record for this injury."""
        return reverse('bleedinfo-detail', args=[str(self.id)])

    # def display_injury_type(self):
    #     """Create a string for the Genre. This is required to display genre in Admin."""
    #     return ', '.join(type_of_injury.name for genre in self.type_of_injury.all()[:3])
    #
    # display_injury_type.short_description = 'Type_Of_Injury'
class DateInput(forms.DateInput):
    input_type = 'date'

class BleedForm(ModelForm):
    class Meta:
        model = BleedInfo
        fields = ['title', 'patient', 'ticket_initated_by', 'summary', 'bleed_type',
                  'bleed_location', 'bleed_location_details', 'when_bleed_occured', 'extra_factor_yn',
                  'num_of_days_extra_factor_was_used', 'did_patient_use_factor_yn', 'why_patinet_did_not_use_facor',
                  'did_patient_use_home_factor_yn', 'home_factor_supply_details']

        widgets = {
            'when_bleed_occured': DateInput(),
        }



class Injury(models.Model):
    """Model representing a book (but not a specific copy of a book)."""
    title = models.CharField(max_length=200)

    # Foreign Key used because book can only have one author, but authors can have multiple books
    # Author as a string rather than object because it hasn't been declared yet in the file
    person = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
# User
    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')

    # ManyToManyField used because genre can contain many books. Books can cover many genres.
    # Genre class has already been defined so we can specify the object above.
#        type_of_injury = models.ManyToManyField(Type_Of_Injury, help_text='Select a type of injury for this incident')
    injury_type = models.IntegerField(choices=BLEED_TYPE, default=1)

    def __str__(self):
        """String for representing the Model object."""
        return self.title

    def get_absolute_url(self):
        """Returns the url to access a detail record for this injury."""
        return reverse('injury-detail', args=[str(self.id)])
        
    def display_injury_type(self):
        """Create a string for the Genre. This is required to display genre in Admin."""
        return ', '.join(type_of_injury.name for genre in self.type_of_injury.all()[:3])

    display_injury_type.short_description = 'Type_Of_Injury'


class InjuryForm(ModelForm):
    class Meta:
        model = Injury
        fields = ['title', 'summary', 'injury_type']
    
class Book(models.Model):
    """Model representing a book (but not a specific copy of a book)."""
    title = models.CharField(max_length=200)

    # Foreign Key used because book can only have one author, but authors can have multiple books
    # Author as a string rather than object because it hasn't been declared yet in the file
    author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
    
    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')
    isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
    
    # ManyToManyField used because genre can contain many books. Books can cover many genres.
    # Genre class has already been defined so we can specify the object above.
    genre = models.ManyToManyField(Genre, help_text='Select a genre for this book')
    
    def __str__(self):
        """String for representing the Model object."""
        return self.title
    
    def get_absolute_url(self):
        """Returns the url to access a detail record for this book."""
        return reverse('book-detail', args=[str(self.id)])
        
    def display_genre(self):
        """Create a string for the Genre. This is required to display genre in Admin."""
        return ', '.join(genre.name for genre in self.genre.all()[:3])
    
    display_genre.short_description = 'Genre'
        
        
import uuid # Required for unique book instances
from datetime import date

class BookInstance(models.Model):
    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library')
    book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
    imprint = models.CharField(max_length=200)
    due_back = models.DateField(null=True, blank=True)
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    
    @property
    def is_overdue(self):
        if self.due_back and date.today() > self.due_back:
            return True
        return False


    LOAN_STATUS = (
        ('m', 'Maintenance'),
        ('o', 'On loan'),
        ('a', 'Available'),
        ('r', 'Reserved'),
    )

    status = models.CharField(
        max_length=1,
        choices=LOAN_STATUS,
        blank=True,
        default='m',
        help_text='Book availability',
    )

    class Meta:
        ordering = ['due_back']
        permissions = (("can_mark_returned", "Set book as returned"),) 

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.id} ({self.book.title})'


class Meta:
    ordering = ['due_back']
    permissions = (("can_mark_returned", "Set book as returned"),)

def __str__(self):
    """String for representing the Model object."""
    return f'{self.id} ({self.book.title})'

class Author(models.Model):
    """Model representing an author."""
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('Died', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']

    def get_absolute_url(self):
        """Returns the url to access a particular author instance."""
        return reverse('author-detail', args=[str(self.id)])

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.last_name}, {self.first_name}'

class Person(models.Model):
    """Model representing an author."""
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('Died', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']

    def get_absolute_url(self):
        """Returns the url to access a particular author instance."""
        return reverse('author-detail', args=[str(self.id)])

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.last_name}, {self.first_name}'
