from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from health_view.crypto_functions import *


class FolderInfo(models.Model):
    """Adding attributes to default model user"""
    patient = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    pub_key = models.CharField(max_length=300, blank=True)
    content_key = models.CharField(max_length=300, blank=True, default="no_key")

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


@receiver(post_save, sender=User)
def create_folderinfo(sender, instance, created, **kwargs):
    """Creates folderinfo when user gets created"""
    if created:
        folderinfo = FolderInfo.objects.create(patient=instance)
        folderinfo.pub_key = make_key_pair_public(folderinfo.patient)
        folderinfo.save()


class Permission(models.Model):
    shortcut = models.CharField(max_length=5)
    permissions = models.CharField(max_length=100)

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


class FolderPart(models.Model):
    shortcut = models.CharField(max_length=3)
    part_name = models.CharField(max_length=40)

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


class License(models.Model):
    """License model which defines rights"""
    patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='patient_id')
    justified = models.ForeignKey(User, default=None, on_delete=models.CASCADE, related_name='justified_id')
    license_creator = models.ForeignKey(User, default=None, null=True, blank=True, on_delete=models.CASCADE, related_name='license_creators')
    exp_date = models.CharField(max_length=200, null=True, blank=True)
    permissions = models.ManyToManyField(Permission)
    folder_parts = models.ManyToManyField(FolderPart)
    signature = models.CharField(max_length=200, null=True)

    def __str__(self):
        """String for representing the Model object."""
        return self.justified.get_username() + "   " + ''.join(p.shortcut for p in self.permissions.all())


