import json

from django import template
from django.utils.safestring import mark_safe
from django.utils.translation import gettext, gettext_noop

from ocyan.core.fender import config

register = template.Library()

gettext_noop("false")
gettext_noop("true")


@register.simple_tag(name="ocyanjson")
def get_value_from_ocyan_json(section, key, fallback=None):
    return config.get(section, key, fallback)


@register.filter
def parse(value):
    return json.loads(value)


def _printable(value):
    if isinstance(value, bool):
        val = json.dumps(value)
        translated_val = gettext(val)
        return '<span class="printable-bool printable-bool-%s">%s</span>' % (
            str(value).lower(),
            translated_val,
        )
    elif isinstance(value, int):
        return '<span class="printable-int">%s</span>' % value
    elif isinstance(value, float):
        return '<span class="printable-float">%s</span>' % value
    elif value is None:
        return '<span class="printable-empty"/>'
    elif isinstance(value, list):
        return '<span class="printable-flattened-list">%s</span>' % ", ".join(
            map(_printable, value)
        )

    return gettext(value)


@register.filter
def printable(value):
    return mark_safe(_printable(value))
