from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import JSONField
from wagtail.snippets.models import register_snippet
from wagtail.search import index
from modelcluster.fields import ParentalKey

from core.mixins import GraphqlNodeMixin


@register_snippet
class Survey(models.Model, index.Indexed, GraphqlNodeMixin):
    title = models.CharField(max_length=255)
    module = models.ForeignKey(
        "books.Module",
        related_name="surveys",
        on_delete=models.PROTECT,
        null=True,
        blank=True,
    )
    data = JSONField()

    @property
    def route(self):
        return f"module/{self.module.slug}#{self.graphql_id}"

    search_fields = [
        index.AutocompleteField("title"),
        index.AutocompleteField("module__meta_title"),
    ]

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["-pk"]


class Answer(models.Model):
    owner = models.ForeignKey(
        get_user_model(), on_delete=models.CASCADE, related_name="answers"
    )
    data = JSONField()
    survey = models.ForeignKey(Survey, on_delete=models.PROTECT, related_name="answers")

    def __str__(self):
        return "{} - {}".format(self.owner.username, self.survey.title)
