# (c) cavaliba.com - home - infodoc.py

"""
Info content: the global Info page HTML (DataRegistry GLOBAL_INFO_CONTENT) and
each schema's info HTML (DataClass.description), as edited by the admin tools
Schema INFO editor. A target is either GLOBAL_TARGET or a schema classname.
"""

from django import forms
from django.utils.translation import gettext_lazy as _
from tinymce.widgets import TinyMCE

import app_home.cache as cache
from app_data.models import DataClass
from app_data.registry import registry_get_key, registry_set_key

GLOBAL_INFO_KEY = "GLOBAL_INFO_CONTENT"

# selector value for the global content: "@" is not a valid classname character
GLOBAL_TARGET = "@global"

# DataRegistry.value max_length; applied to schema info too
INFO_MAX_LENGTH = 50000


class InfoContentForm(forms.Form):
    """HTML content of one info target, edited with TinyMCE."""

    content = forms.CharField(
        max_length=INFO_MAX_LENGTH,
        required=False,
        label=_("Content"),
        widget=TinyMCE(attrs={"cols": 80, "rows": 30}),
    )


def info_get(target):
    """Return the HTML content of a target, or None for an unknown schema."""

    if target == GLOBAL_TARGET:
        return registry_get_key(GLOBAL_INFO_KEY) or ""

    obj = DataClass.objects.filter(keyname=target).first()
    if not obj:
        return None
    return obj.description or ""


def info_set(target, content):
    """Store the HTML content of a target; return False for an unknown schema.

    A schema update writes the description column only (not Schema.save(), which
    rewrites the whole schema) and drops the cached Schema."""

    if target == GLOBAL_TARGET:
        registry_set_key(GLOBAL_INFO_KEY, content)
        return True

    if not DataClass.objects.filter(keyname=target).update(description=content):
        return False
    cache.cache2_schema.delete(target)
    return True
