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 gettext as _, get_language
from django import http
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import check_for_language
from django.template.loader import TemplateDoesNotExist, get_template, select_template
from django.template import Template
from django.template.response import TemplateResponse
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 url_has_allowed_host_and_scheme(url=next, allowed_hosts={request.get_host()}):
        next = request.META.get('HTTP_REFERER')
        if not url_has_allowed_host_and_scheme(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,
            secure=settings.LANGUAGE_COOKIE_SECURE,
            httponly=settings.LANGUAGE_COOKIE_HTTPONLY,
            samesite=settings.LANGUAGE_COOKIE_SAMESITE,
        )
    return response


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

    basename = 'pages/' + name

    # Try to render a HTML template
    try:
        html_template = get_template(basename + '.html')
        return TemplateResponse(request, html_template).render()
    except TemplateDoesNotExist:
        pass

    try:
        md_template = select_template([
            basename + '.' + get_language() + '.md',
            basename + '.en.md',
        ])
    except TemplateDoesNotExist:
        return HttpResponseNotFound("Page not found")

    page_source = md_template.render(None, request)
    page_fm = frontmatter.loads(page_source)
    page_md = page_fm.content

    title = page_fm.metadata.get('Title', "")
    md_inst = markdown.Markdown(extensions=[
        'markdown.extensions.meta',
        CodeHiliteExtension(noclasses=True),
    ])
    page_html = md_inst.convert(page_md)

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

