# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

'''Simplify rendering of template to produce text values.

Disable autoescaping.
'''

from django.core.exceptions import ValidationError
from django.template import TemplateSyntaxError
from django.template.backends.django import DjangoTemplates
from django.utils.translation import gettext as _


def make_template(template_string):
    engine = DjangoTemplates(
        {
            'NAME': 'django',
            'DIRS': [],
            'APP_DIRS': False,
            'OPTIONS': {'autoescape': False},
        }
    )
    return engine.from_string(template_string)


def render_to_string(template_string, context):
    return make_template(template_string).render(context=context)


def validate_template(template_string):
    try:
        make_template(template_string)
    except TemplateSyntaxError as e:
        raise ValidationError(_('Invalid template: %s') % e)
