# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import jinja2

from distribution.utils import (
    date_to_rfc2822_string,
    sanitize_xml_text,
    invalid_xml_remove
)


@jinja2.environmentfilter
def invalid_xml_remove_filter(env, text):
    if text:
        return invalid_xml_remove(text)
    return text


@jinja2.environmentfilter
def sanitize_xml_text_filter(env, text):
    return sanitize_xml_text(text)


@jinja2.environmentfilter
def date_to_rfc2822_string_filter(env, date):
    return date_to_rfc2822_string(date)


FILTERS = jinja2.filters.FILTERS
FILTERS.update({'sanitize_xml_text': sanitize_xml_text_filter,
                'invalid_xml_remove': invalid_xml_remove_filter,
                'date_to_rfc2822_string': date_to_rfc2822_string_filter})


# tojson isn't automatically added to custom environments
if 'tojson' not in FILTERS:
    from flask import json
    FILTERS['tojson'] = json.tojson_filter
