from django.shortcuts import render, redirect
from django.http import HttpResponse

from django.template import Template
from django.template import Context
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required

from django.views.defaults import page_not_found

import markdown
from bs4 import BeautifulSoup

from .models import Site, Page, Image

_TEMPLATE = """                          
<!DOCTYPE html>
<html>
<head>
    {{site_header | safe}}
</head>
<body>
    {{page_body | safe}}
</body>

</html>
"""

def handler404(request, exception, template_name="404.html"):
    page_names = ["home", "schedule", "thingstodo", "afters"]
    working_path = request.path.lower()
    if working_path and working_path[0] == "/":
        working_path = working_path[1:]
    if working_path and working_path[-1] == "/":
        working_path = working_path[:-1]
    if working_path in page_names:
        return redirect(working_path)
    return page_not_found(request, exception, template_name)

def get_site_header(site):
    template = Template(site.header)
    context = Context({"site": site})
    return template.render(context)

def get_index_body(site):
    template = Template(site.index)
    context = Context({"site": site})
    return template.render(context)

def index(request):
    site = Site.objects.get(pk=1)

    template = Template(_TEMPLATE)
    context = Context({"site": site, 
        "site_header" : get_site_header(site),
        "page_body" : get_index_body(site)})

    soup = BeautifulSoup(template.render(context))
    return HttpResponse(soup.prettify())

def login_view(request):
    if request.method == "GET":
        token = request.GET["token"]
    else:
        token = request.POST["token"]
    user = authenticate(request, username="guest", password=token.lower())
    if user is not None:
        login(request, user)
        return redirect("home")
    else:
        return redirect("index")

@login_required(login_url="/")
def home(request):
    return get_page("Home")  

@login_required(login_url="/")
def afters(request):
    return get_page("Afters")  

def get_page_header(site: Site):

    pages = site.page_set.order_by("priority").filter(navigable=True)
    template = Template(site.page_header)
    context = Context({"pages" : pages})  
    return template.render(context)

def get_page_body(site: Site, page: Page):

    header = get_page_header(site)
    body = f"<div class=article-content>{markdown.markdown(page.content)}</div>"
    return header + body

def get_page(name:str):
    site = Site.objects.get(pk=1)
    page = Page.objects.get(name__iexact=name)

    template = Template(_TEMPLATE)
    context = Context({"site": site, 
        "site_header" : get_site_header(site),
        "page_body" : get_page_body(site, page)})

    content = template.render(context)
    soup = BeautifulSoup(content, features="html.parser")

    for img in soup.find_all('img'):
        img_name = img["src"]
        db_images = Image.objects.filter(name=img_name)
        if db_images:
            url = db_images[0].content.url.replace("uploads/","")
            img["src"] = url

    return HttpResponse(soup.prettify())

@login_required(login_url="/")
def schedule(request):
    return get_page("Schedule")

@login_required(login_url="/")
def things_to_do(request):
    return get_page("ThingsToDo")   

@login_required(login_url="/")
def travel(request):
    return get_page("Travel")   

@login_required(login_url="/")
def faq(request):
    return get_page("FAQ")   

@login_required(login_url="/")
def accommodation(request):
    return get_page("Accommodation")  

