import os.path
import re

import markdown
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.extensions.toc import TocExtension
from django.http import HttpResponseNotFound
from django.shortcuts import render
from django.conf import settings
from django.utils.translation import ugettext as _, get_language
from django import http
from django.utils.http import is_safe_url
from django.utils.translation import (
    LANGUAGE_SESSION_KEY, check_for_language,
)
from django.template.loader import TemplateDoesNotExist, get_template
from django.template import Template
import django_lcore
from constance import config
import frontmatter

from downloads.models import Version
from .common import get_price_float


@django_lcore.APICache(initial=[])
def get_gateway_locations():
    gateways = django_lcore.api.get("gateways/", enabled=True)
    locations = set()

    for gw in gateways.list_iter():
        if not gw["tags"]:
            continue
        loc = gw["tags"].get("location")
        if not loc:
            continue
        locations.add((loc["lat"], loc["lon"]))

    return list(locations)


def index(request):
    return render(request, 'ccvpn/index.html', {
        "eur_price": '%.2f' % get_price_float(),
        "motd": config.MOTD,
        "gateway_locations": get_gateway_locations(),
    })


def chat(request):
    if request.user.is_authenticated:
        username = request.user.username + '|cc'
    else:
        username = "cc?"
    ctx = dict(username=username, title=_("Live Chat"))
    return render(request, 'ccvpn/chat.html', ctx)


def set_lang(request):
    """ django.views.i18n.set_language() with GET """

    next = request.GET.get('next', request.GET.get('next'))
    if not is_safe_url(url=next, allowed_hosts={request.get_host()}):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, allowed_hosts={request.get_host()}):
            next = '/'
    response = http.HttpResponseRedirect(next)
    lang_code = request.GET.get('lang', None)
    if lang_code and check_for_language(lang_code):
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                            max_age=settings.LANGUAGE_COOKIE_AGE,
                            path=settings.LANGUAGE_COOKIE_PATH,
                            domain=settings.LANGUAGE_COOKIE_DOMAIN)
    return response


def page(request, name):
    if not re.match('^[a-z0-9_-]{1,50}$', name):
        return HttpResponseNotFound()

    basename = 'pages/' + name

    # For "pages", entire files are translated. We try the most
    # specific first
    files = [
        basename + '.' + get_language() + '.md',
        basename + '.en.md',
        basename + '.md',
    ]

    for file in files:
        try:
            template = get_template(file)
        except TemplateDoesNotExist:
            continue

        page_source = template.render(None, request)
        page = frontmatter.loads(page_source)
        page_md = page.content

        title = page.metadata.get('Title', "")
        toc_depth = int(page.metadata.get('TocDepth', 6))

        md = markdown.Markdown(extensions=[
            TocExtension(toc_depth=toc_depth),
            'markdown.extensions.meta',
            CodeHiliteExtension(noclasses=True),
        ])
        page_html = md.convert(page_md)


        ctx = dict(content=page_html, title=title)
        return render(request, 'ccvpn/page.html', ctx)

    return HttpResponseNotFound()

