from django import template
import json
import re

register = template.Library()


@register.filter
def pretty_json(value):
    try:
        if isinstance(value, str):
            data = json.loads(value)
        else:
            data = value
        return json.dumps(data, indent=2)
    except (ValueError, TypeError):
        return value


def _unescape_control_sequences(text):
    text = re.sub(r"(?<!\\)\\r\\n", "\r\n", text)
    text = re.sub(r"(?<!\\)\\n", "\n", text)
    text = re.sub(r"(?<!\\)\\r", "\r", text)
    return re.sub(r"(?<!\\)\\t", "\t", text)


@register.filter
def unescape_control_sequences(value):
    if not isinstance(value, str):
        return value
    return _unescape_control_sequences(value)


@register.filter
def pretty_json_display(value):
    try:
        if isinstance(value, str):
            data = json.loads(value)
        else:
            data = value
        pretty = json.dumps(data, indent=2)
        return _unescape_control_sequences(pretty)
    except (ValueError, TypeError):
        return value
