# -*- coding: utf-8 -*-

import pytest

from quixote import cleanup
from qommon.template import Template, TemplateError

from utilities import create_temporary_pub, clean_temporary_pub


def setup_module(module):
    cleanup()
    global pub
    pub = create_temporary_pub()


def teardown_module(module):
    clean_temporary_pub()


def test_template():
    tmpl = Template('')
    assert tmpl.render() == ''
    assert tmpl.render({'foo': 'bar'}) == ''
    tmpl = Template('zoo')
    assert tmpl.render() == 'zoo'
    assert tmpl.render({'foo': 'bar'}) == 'zoo'

    # django
    tmpl = Template('{{ foo }}')
    assert tmpl.render() == ''
    assert tmpl.render({'foo': 'bar'}) == 'bar'
    tmpl = Template('{% if foo %}{{ foo }}{% endif %}')
    assert tmpl.render() == ''
    assert tmpl.render({'foo': 'bar'}) == 'bar'

    # ezt
    tmpl = Template('[foo]')
    assert tmpl.render() == '[foo]'
    assert tmpl.render({'foo': 'bar'}) == 'bar'
    tmpl = Template('[if-any foo][foo][end]')
    assert tmpl.render() == ''
    assert tmpl.render({'foo': 'bar'}) == 'bar'

    # mix Django/ezt: Django wins
    tmpl = Template('{% if foo %}{{ foo }}[foo]{% endif %}')
    assert tmpl.render({'foo': 'bar'}) == 'bar[foo]'

    # django syntax error
    with pytest.raises(TemplateError):
        tmpl = Template('{% if foo %}{{ foo }}{% end %}', raises=True)
    tmpl = Template('{% if foo %}{{ foo }}{% end %}')
    assert tmpl.render({'foo': 'bar'}) == '{% if foo %}{{ foo }}{% end %}'

    # ezt syntax error
    with pytest.raises(TemplateError):
        tmpl = Template('[if-any foo][foo][endif]', raises=True)
    tmpl = Template('[if-any foo][foo][endif]')
    assert tmpl.render({'foo': 'bar'}) == '[if-any foo][foo][endif]'


def test_template_encoding():
    # django
    tmpl = Template('{{ foo }} à vélo')
    assert tmpl.render() == ' à vélo'
    assert tmpl.render({'foo': 'fou'}) == 'fou à vélo'
    assert tmpl.render({'foo': 'félé'}) == 'félé à vélo'

    tmpl = Template("{% if foo == 'félé' %}à vélo{% endif %}")
    assert tmpl.render() == ''
    assert tmpl.render({'foo': 'fou'}) == ''
    assert tmpl.render({'foo': 'félé'}) == 'à vélo'

    # ezt
    tmpl = Template('[foo] à vélo')
    assert tmpl.render() == '[foo] à vélo'
    assert tmpl.render({'foo': 'fou'}) == 'fou à vélo'
    assert tmpl.render({'foo': 'félé'}) == 'félé à vélo'


def test_datetime_templatetags():
    tmpl = Template('{% load qommon %}{{ plop|parse_datetime|date:"d" }}')
    assert tmpl.render({'plop': '2017-12-21 10:32'}) == '21'
    assert tmpl.render({'plop': 'x'}) == ''

    tmpl = Template('{% load qommon %}{{ plop|parse_date|date:"d" }}')
    assert tmpl.render({'plop': '2017-12-21'}) == '21'
    assert tmpl.render({'plop': 'x'}) == ''

    tmpl = Template('{% load qommon %}{{ plop|parse_time|date:"H" }}')
    assert tmpl.render({'plop': '10:32'}) == '10'
    assert tmpl.render({'plop': 'x'}) == ''
