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


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

    search_fields = [
        index.SearchField('title', partial_match=True),
        index.SearchField('module__meta_title', partial_match=True),
    ]

    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.CASCADE, related_name='answers')

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