import logging

from easy_thumbnails.fields import ThumbnailerImageField

from django.contrib.auth.models import User
from django.core.validators import ValidationError, validate_email
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _

from .managers import (
    ActiveJobMemberManager,
    InactiveJobMemberManager,
    JobMemberManager,
    JobGroupManager,
    MemberManager,
)
from .validators import (
    PhoneNumberValidator,
    validate_domainonly_email,
    validate_file_size,
    validate_image_dimension,
)

logger = logging.getLogger(__name__)


class Member(models.Model):
    firstname = models.CharField("Vorname", max_length=128)
    surname = models.CharField("Nachname", max_length=128)
    nickname = models.CharField("Spitzname", max_length=128)

    # LDAP Username
    username = models.CharField("fet.at Benutzername", max_length=128, blank=True)

    # fet mail account
    mailaccount = models.CharField(
        "Mailadresse",
        unique=True,
        max_length=128,
        validators=[validate_email, validate_domainonly_email],
        error_messages={
            "unique": _("Diese Mailadresse existiert schon."),
        },
    )

    class MemberRole(models.TextChoices):
        ACTIVE = "A", _("Active")
        PENSION = "P", _("Pension")

    role = models.CharField(
        "Rolle",
        max_length=1,
        choices=MemberRole.choices,
        default=MemberRole.ACTIVE,
    )

    description = models.TextField(null=True, blank=True)

    image = ThumbnailerImageField(
        upload_to="uploads/members/image/",
        validators=[validate_file_size, validate_image_dimension],
    )

    birthday = models.DateField(null=True, blank=True)

    phone = models.CharField(
        max_length=17,
        blank=True,
        validators=[PhoneNumberValidator()],
    )

    address = models.TextField(null=True, blank=True)

    date_modified = models.DateTimeField(auto_now=True)
    date_created = models.DateTimeField(auto_now_add=True)

    # Managers
    objects = models.Manager()
    all_members = MemberManager()

    class Meta:
        verbose_name = "Mitglied"
        verbose_name_plural = "Mitglieder"

    def __str__(self):
        return self.firstname + " " + self.surname

    # need to have 'View on site' link in admin app
    def get_absolute_url(self):
        return reverse("member", kwargs={"member_id": self.id})

    def clean(self):
        if not self.image:
            raise ValidationError(_("Es fehlt das Profilbild."))

        if self.username:
            try:
                user = User.objects.get(username=self.username.lower())
            except User.DoesNotExist as e:
                logger.info("Username does not exist. Error: {}".format(e))
            else:
                user.first_name = self.firstname
                user.save()


class JobGroup(models.Model):
    name = models.CharField(max_length=128)

    shortterm = models.CharField(max_length=128)
    slug = models.SlugField(unique=True, null=True, blank=True)

    description = models.TextField(null=True, blank=True)

    is_pinned = models.BooleanField(verbose_name="ANGEHEFTET", default=False)

    # Managers
    objects = models.Manager()
    all_jobgroups = JobGroupManager()

    class Meta:
        verbose_name = "Tätigkeitsbereich"
        verbose_name_plural = "Tätigkeitsbereiche"

    def __str__(self):
        return self.name

    # need to have 'View on site' link in admin app
    def get_absolute_url(self):
        return reverse("jobs", kwargs={"slug": self.slug})

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.shortterm)

        super().save(*args, **kwargs)


class Job(models.Model):
    name = models.CharField(max_length=128)

    shortterm = models.CharField(max_length=128)
    slug = models.SlugField(unique=True, null=True, blank=True)

    job_group = models.ForeignKey(
        JobGroup,
        on_delete=models.CASCADE,
        verbose_name="Job Gruppe",
    )

    # Managers
    objects = models.Manager()

    class Meta:
        verbose_name = "Tätigkeit"
        verbose_name_plural = "Tätigkeiten"

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("jobs", kwargs={"slug": self.job_group.slug}) + "#" + self.slug

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.shortterm)

        super().save(*args, **kwargs)


class JobMember(models.Model):
    member = models.ForeignKey(
        Member,
        on_delete=models.CASCADE,
        verbose_name="Mitglied",
    )
    job = models.ForeignKey(
        Job,
        on_delete=models.CASCADE,
        verbose_name="Tätigkeit",
    )

    job_start = models.DateField("Job Start")
    job_end = models.DateField("Job Ende", null=True, blank=True)

    class JobRole(models.TextChoices):
        PRESIDENT = ("10", _("Vorsitz"))
        VICE_PRESIDENT = ("20", _("Stv. Vorsitz"))
        SECOND_VICE_PRESIDENT = ("30", _("2. Stv. Vorsitz"))
        PERSON_RESPONSIBLE = ("40", _("Verantwortliche_r"))
        MEMBER = ("50", _("Mitglied"))
        SUBSTITUTE_MEMBER = ("60", _("Ersatzmitglied"))

    job_role = models.CharField(
        max_length=2, choices=JobRole.choices, default=JobRole.MEMBER
    )

    objects = models.Manager()
    members = JobMemberManager()
    active_member = ActiveJobMemberManager()
    inactive_member = InactiveJobMemberManager()

    def __str__(self):
        return self.job.name
