MULTISEEK_REPORT_TYPE = "_ms_report_type" class SearchForm(models.Model):
    name = models.TextField(verbose_name=_("Name"), unique=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,
                              on_delete=models.CASCADE)
    public = models.BooleanField(
        verbose_name=_("Public"),
        default=False, help_text=_(
            "Make this search publicly available?"))
    data = models.TextField(verbose_name=_("Form data (JSON)"))

    objects = SearchFormManager()

    class Meta:
        ordering = ['name',]

    def __str__(self):
        return self.name AND = "and" AUTOCOMPLETE = "autocomplete" MULTISEEK_ORDERING_PREFIX = "order_" OR = "or" VALUE_LIST = "value-list" class ParseError(Exception):
    pass class UnknownField(Exception):
    pass class UnknownOperation(Exception):
    pass def get_registry(registry):
    """
    :rtype: MultiseekRegistry
    """

    if isinstance(registry, str):
        if registry not in _cached_registry:
            m = importlib.import_module(registry).registry
            _cached_registry[registry] = m
        return _cached_registry[registry]

    return registry
import json
from builtins import str as text
from django import http, shortcuts
from django.db import transaction
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http.response import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext_lazy
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.generic import ListView, TemplateView
from multiseek.logic import MULTISEEK_REPORT_TYPE
from multiseek.models import SearchForm
from .logic import (
    AND,
    AUTOCOMPLETE,
    MULTISEEK_ORDERING_PREFIX,
    OR,
    VALUE_LIST,
    ParseError,
    UnknownField,
    UnknownOperation,
    get_registry,
)
# -*- encoding: utf-8 -*-






SAVED = "saved"
OVERWRITE_PROMPT = "overwrite-prompt"

ERR_FORM_NAME = _("Form name must not be empty")
ERR_LOADING_DATA = _("Error while loading form data")
ERR_PARSING_DATA = _("Error while parsing form data")
ERR_NO_FORM_DATA = _("No form data provided")

MULTISEEK_SESSION_KEY = "multiseek_json"
MULTISEEK_SESSION_KEY_REMOVED = "multiseek_json_removed"


def reverse_or_just_url(s):
    if s.startswith("/"):
        return s
    return reverse(s)


LAST_FIELD_REMOVE_MESSAGE = _("The ability to remove the last field has been disabled.")


def user_allowed_to_save_forms(user):
    if hasattr(user, "is_staff"):
        return user.is_staff


class MultiseekPageMixin:
    registry = None


class MultiseekFormPage(MultiseekPageMixin, TemplateView):
    """
    This view renders multiseek form and javascript required to manipulate
    it.
    """

    def get_context_data(self):
        registry = get_registry(self.registry)

        fields = registry.get_fields(self.request)

        js_fields = json.dumps([text(x.label) for x in fields])
        js_ops = json.dumps(
            dict([(text(f.label), [text(x) for x in f.ops]) for f in fields])
        )
        js_types = json.dumps(dict([(text(f.label), f.type) for f in fields]))

        js_autocompletes = json.dumps(
            dict(
                [
                    (text(field.label), reverse_or_just_url(field.get_url()))
                    for field in registry.field_by_type(AUTOCOMPLETE, self.request)
                ]
            )
        )

        def get_values(values):
            if callable(values):
                return values()
            return values

        js_value_lists = json.dumps(
            dict(
                [
                    (text(field.label), [text(x) for x in get_values(field.values)])
                    for field in registry.field_by_type(VALUE_LIST, self.request)
                ]
            )
        )

        initialize_empty_form = True
        form_data = self.request.session.get(MULTISEEK_SESSION_KEY, {})
        if form_data:
            form_data = json.loads(form_data)
            initialize_empty_form = False
        js_init = registry.recreate_form(form_data)

        js_removed = ",".join(
            '"%(x)s"' % dict(x=x)
            for x in self.request.session.get(MULTISEEK_SESSION_KEY_REMOVED, [])
        )
        return dict(
            js_fields=js_fields,
            js_ops=js_ops,
            js_types=js_types,
            js_autocompletes=js_autocompletes,
            js_value_lists=js_value_lists,
            js_and=AND,
            js_or=OR,
            js_init=js_init,
            js_remove_message=LAST_FIELD_REMOVE_MESSAGE,
            js_removed=js_removed,
            user_allowed_to_save_forms=user_allowed_to_save_forms(self.request.user),
            initialize_empty_form=initialize_empty_form,
            order_boxes=registry.order_boxes,
            ordering=registry.ordering,
            report_types=registry.get_report_types(self.request),
            saved_forms=SearchForm.objects.get_for_user(self.request.user),

            MULTISEEK_ORDERING_PREFIX=MULTISEEK_ORDERING_PREFIX,