from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _

from vbv_lernwelt.core.models import User
from vbv_lernwelt.course.models import CourseSessionUser
from vbv_lernwelt.notify.service import NotificationService


class FeedbackIntegerField(models.IntegerField):
    def __init__(self, **kwargs):
        validators = kwargs.pop("validators", [])
        nullable = kwargs.pop("null", True)
        super().__init__(
            validators=validators + [MinValueValidator(1), MaxValueValidator(4)],
            null=nullable,
            **kwargs,
        )


class FeedbackResponse(models.Model):
    class DiscoveredChoices(models.TextChoices):
        INTERNET = "I", _("Internet")
        LEAFLET = "L", _("Leaflet")
        NEWSPAPER = "N", _("Newspaper")
        RECOMMENDATION = "R", _("Personal recommendation")
        EVENT = "E", _("Public event")
        OTHER = "O", _("Other")

    class RatingChoices(models.IntegerChoices):
        ONE = 1, "1"
        TWO = 2, "2"
        THREE = 3, "3"
        FOUR = 4, "4"

    class PercentageChoices(models.IntegerChoices):
        TWENTY = 20, "20%"
        FOURTY = 40, "40%"
        SIXTY = 60, "60%"
        EIGHTY = 80, "80%"
        HUNDRED = 100, "100%"

    def save(self, *args, **kwargs):
        if not self.id:
            course_session_users = CourseSessionUser.objects.filter(
                role="EXPERT", course_session=self.course_session, expert=self.circle
            )
            for csu in course_session_users:
                NotificationService.send_information_notification(
                    recipient=csu.user,
                    verb=f"{_('New feedback for circle')} {self.circle.title}",
                    target_url=f"/course/{self.course_session.course.slug}/cockpit/feedback/{self.circle_id}/",
                )
        super(FeedbackResponse, self).save(*args, **kwargs)

    data = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)

    circle = models.ForeignKey("learnpath.Circle", models.PROTECT)
    course_session = models.ForeignKey("course.CourseSession", models.PROTECT)
