import uuid

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models import JSONField


class Organisation(models.Model):
    organisation_id = models.IntegerField(primary_key=True)
    name_de = models.CharField(max_length=255)
    name_fr = models.CharField(max_length=255)
    name_it = models.CharField(max_length=255)

    def __str__(self):
        return f"{self.name_de} ({self.organisation_id})"

    class Meta:
        verbose_name = "Organisation"
        verbose_name_plural = "Organisations"
        ordering = ["organisation_id"]


class User(AbstractUser):
    """
    Default custom user model for VBV Lernwelt.
    If adding fields that need to be filled at user signup,
    """

    LANGUAGE_CHOICES = (
        ("de", "Deutsch"),
        ("fr", "Français"),
        ("it", "Italiano"),
    )

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    avatar_url = models.CharField(
        max_length=254, blank=True, default="/static/avatars/myvbv-default-avatar.png"
    )
    email = models.EmailField("email address", unique=True)
    sso_id = models.UUIDField(
        "SSO subscriber ID", unique=True, null=True, blank=True, default=None
    )
    additional_json_data = JSONField(default=dict, blank=True)
    language = models.CharField(max_length=2, choices=LANGUAGE_CHOICES, default="de")

    organisation = models.ForeignKey(
        Organisation, on_delete=models.SET_NULL, null=True, blank=True
    )


class SecurityRequestResponseLog(models.Model):
    label = models.CharField(max_length=255, blank=True, default="")

    request_method = models.CharField(max_length=255, blank=True, default="")
    request_full_path = models.CharField(max_length=255, blank=True, default="")
    request_username = models.CharField(max_length=255, blank=True, default="")
    request_client_ip = models.CharField(max_length=255, blank=True, default="")

    response_status_code = models.CharField(max_length=255, blank=True, default="")

    additional_json_data = JSONField(default=dict, blank=True)


class JobLog(models.Model):
    started = models.DateTimeField(auto_now_add=True)
    ended = models.DateTimeField(blank=True, null=True)
    job_name = models.CharField(max_length=255)
    success = models.BooleanField(default=False)
    error_message = models.TextField(blank=True, default="")
    stack_trace = models.TextField(blank=True, default="")
    json_data = models.JSONField(default=dict)

    def __str__(self):
        return "{job_name} {started:%H:%M %d.%m.%Y}".format(**self.__dict__)
