# coding: utf-8

import os.path

from datetime import datetime
from django.conf import settings
from django.test.client import RequestFactory
from django.test.utils import override_settings

import pytest
from django_jinja.backend import Jinja2
from jinja2 im
port Markup
from mock import patch
from pyquery import PyQuery as pq

from bedrock.base.templatetags.helpers import static
from bedrock.mozorg.templatetags import misc
from bedrock.mozorg.tests import TestCase
from lib.l10n_utils.fluent import fluent_l10n


TEST_FILES_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                               'test_files')
TEST_L10N_MEDIA_PATH = os.path.join(TEST_FILES
_ROOT, 'media', '%s', 'l10n')

TEST_DONATE_LINK = ('https://donate.mozilla.org/{locale}/'
                    '?presets={presets}&amount={default}'
                    '&utm_source=mozilla.org&utm_medium=referral&utm_content={source}'
                    '&currency={currency}')

TEST_DONATE_PARAMS = {
    'en-US': {
        'currency': 'usd',
        'presets': '100,50,25,15',
        'default': '50'
    },
    'es-MX': {
        'currency': 'eur',
        'presets': '100,50,25,15',
        'default': '15'
    },
}

TEST_FIREFOX_TWITTER_ACCOUNTS = {
    'en-US': 'https://twitter.com/firefox',
    'es-ES': 'https://twitter.com/firefox_es',
    'pt-BR': 'https://twitter.com/firefoxbrasil',
}

TEST_FXA_ENDPOINT = 'https://accounts.firefox.com/'
TEST_FXA_MOZILLAONLINE_ENDPOINT = 'https://accounts.firefox.com.cn/'

jinja_env = Jinja2.get_default()


# Where should this function go?
def render(s, context=None):
    t = jinja_env.from_string(s)
    return t.render(context or {})


def test_convert_to_high_res():
    assert misc.convert_to_high_res('/media/img/the.dude.png') == '/media/img/the.dude-high-res.png'
    assert misc.convert_to_high_res('/media/thats-a-bummer-man.jpg') == '/media/thats-a-bummer-man-high-res.jpg'


@patch('bedrock.mozorg.templatetags.misc._l10n_media_exists')
@patch('django.conf.settings.LANGUAGE_CODE', 'en-US')
class TestImgL10n(TestCase):
    rf = RequestFactory()

    def _render(self, locale, url):
        req = self.rf.get('/')
        req.locale = locale
        return render("{{{{ l10n_img('{0}') }}}}".format(url),
                      {'request': req})

    def test_works_for_default_lang(self, media_exists_mock):
        """Should output correct path for default lang always."""
        media_exists_mock.return_value = True
        assert self._render('en-US', 'dino/head.png') == static('img/l10n/en-US/dino/head.png')
        assert self._render('en-US', 'img/dino/head.png') == static('img/l10n/en-US/dino/head.png')

        assert self._render('en-US', 'dino/does-not-exist.png') == static('img/l10n/en-US/dino/does-not-exist.png')

    def test_works_for_other_lang(self, media_exists_mock):
        """Should use the request lang if file exists."""
        media_exists_mock.return_value = True
        assert self._render('de', 'dino/head.png') == static('img/l10n/de/dino/head.png')
        assert self._render('de', 'img/dino/head.png') == static('img/l10n/de/dino/head.png')

    def test_defaults_when_lang_file_missing(self, media_exists_mock):
        """Should use default lang when file doesn't exist for lang."""
        media_exists_mock.return_value = False
        assert self._render('is', 'dino/head.png') == static('img/l10n/en-US/dino/head.png')

    def test_latam_spanishes_fallback_to_european_spanish(self, media_exists_mock):
        """Should use es-ES image when file doesn't exist for lang."""
        media_exists_mock.side_effect = [False, True]
        assert self._render('es-AR', 'dino/head.png') == static('img/l10n/es-ES/dino/head.png')

        media_exists_mock.reset_mock()
        media_exists_mock.side_effect = [False, True]
        assert self._render('es-CL', 'dino/head.png') == static('img/l10n/es-ES/dino/head.png')

        media_exists_mock.reset_mock()
        media_exists_mock.side_effect = [False, True]
        assert self._render('es-MX', 'dino/head.png') == static('img/l10n/es-ES/dino/head.png')

        media_exists_mock.reset_mock()
        media_exists_mock.side_effect = [False, True]
        assert self._render('es', 'dino/head.png') == static('img/l10n/es-ES/dino/head.png')

    def test_file_not_checked_for_default_lang(self, media_exists_mock):
        """
        Should not check filesystem for default lang, but should for others.
        """
        assert self._render('en-US', 'dino/does-not-exist.png') == static('img/l10n/en-US/dino/does-not-exist.png')
        assert not media_exists_mock.called

        self._render('is', 'dino/does-not-exist.png')
        media_exists_mock.assert_called_once_with('img', 'is', 'dino/does-not-exist.png')


@override_settings(DEBUG=False)
@patch('bedrock.mozorg.templatetags.misc._l10n_media_exists')
class TestL10nCSS(TestCase):
    rf = RequestFactory()
    static_url_dev = '/static/'
    cdn_url = '//mozorg.cdn.mozilla.net'
    static_url_prod = cdn_url + static_url_dev
    markup = ('<link rel="stylesheet" media="screen,projection,tv" href='
              '"%scss/l10n/%s/intl.css">')

    def _render(self, locale):
        req = self.rf.get('/')
        req.locale = locale
        return render('{{ l10n_css() }}', {'request': req})

    @override_settings(DEV=True)
    @patch('django.contrib.staticfiles.storage.staticfiles_storage.base_url', static_url_dev)
    def test_dev_when_css_file_exists(self, media_exists_mock):
        """Should output a path to the CSS file if exists."""
        media_exists_mock.return_value = True
        assert self._render('de') == self.markup % (self.static_url_dev, 'de')
        assert self._render('es-ES') == self.markup % (self.static_url_dev, 'es-ES')

    @override_settings(DEV=True)
    def test_dev_when_css_file_missing(self, media_exists_mock):
        """Should output nothing if the CSS file is missing."""
        media_exists_mock.return_value = False
        assert self._render('en-US') == ''
        assert self._render('fr') == ''

    @override_settings(DEV=False)
    @patch('django.contrib.staticfiles.storage.staticfiles_storage.base_url', static_url_prod)
    def test_prod_when_css_file_exists(self, media_exists_mock):
        """Should output a path to the CSS file if exists."""
        media_exists_mock.return_value = True
        assert self._render('de') == self.markup % (self.static_url_prod, 'de')
        assert self._render('es-ES') == self.markup % (self.static_url_prod, 'es-ES')

    @override_settings(DEV=False)
    def test_prod_when_css_file_missing(self, media_exists_mock):
        """Should output nothing if the CSS file is missing."""
        media_exists_mock.return_value = False
        assert self._render('en-US') == ''
        assert self._render('fr') == ''


class TestVideoTag(TestCase):
    rf = RequestFactory()
    # Video stubs
    moz_video = 'http://videos.mozilla.org/serv/flux/example.%s'
    nomoz_video = 'http://example.org/example.%s'

    def get_l10n(self, locale):
        return fluent_l10n([locale, 'en'], settings.FLUENT_DEFAULT_FILES)

    def _render(self, template):
        req = self.rf.get('/')
        req.locale = 'en-US'
        return render(template, {'request': req, 'fluent_l10n': self.get_l10n(req.locale)})

    def test_empty(self):
        # No video, no output.
        assert render('{{ video() }}') == ''

    def test_video(self):
        # A few common variations
        videos = [self.nomoz_video % ext for ext in ('ogv', 'mp4', 'webm')]
        doc = pq(self._render("{{ video%s }}" % str(tuple(videos))))

        # Tags generated?
        assert doc('video').length == 1
        assert doc('video source').length == 3

        # Extensions in the right order?
        extensions = [os.path.splitext(el.attrib['src'])[1] for el in doc('video source')]
        assert extensions == ['.webm', '.ogv', '.mp4']

    def test_prefix(self):
        # Prefix should be applied to all videos.
        doc = pq(self._render(
            "{{ video('meh.mp4', 'meh.ogv', prefix='http://example.com/blah/') }}")
        )
        assert [el.attrib['src'] for el in doc('video sour