# -*- coding: UTF-8 -*-

from flask import Flask, render_template, Markup, redirect, request, send_file, send_from_directory
from datetime import datetime
from markdown2 import markdown
from os.path import exists, splitext
import json
from pathlib import Path

app = Flask(__name__, static_url_path="", static_folder="static")

file_exts = [".html", ".md", ".txt", ".pdf", ""]

dtformat = "%Y-%m-%d %H:%M"


@app.context_processor
def inject_now():
    return {'now': datetime.utcnow(),
            'tijden': Markup(markdown("".join(open("data/tijden.md", encoding="UTF-8").readlines()))),
            'nieuws': Markup(markdown("".join(open("data/nieuws.md", encoding="UTF-8").readlines())))}


@app.route('/')
def index():
    path = Path("data.json")
    if path.exists():
        with open('data.json') as f:
            try:
                data = json.load(f)
                print(data)

                toload = data["default"]
                for time in data["list"]:
                    print(time)
                    dt = datetime.strptime(time, dtformat)
                    if dt < datetime.now():
                        toload = data["list"][time]

                return render_template("index.html",
                                       content=markdown("".join(open("data/" + toload, encoding="UTF-8").readlines())))

            except json.decoder.JSONDecodeError:
                pass

    return render_template("index.html",
                           content=markdown("".join(open("data/content.md", encoding="UTF-8").readlines())))


@app.route("/<string:url>")
def site(url: str):
    # error handling
    if url.startswith("hoofdexpo") or url.startswith("fotos"):
        return redirect("/schilderijen", 301)
    if url.startswith("boek&foto"):
        return redirect("/boekenmeer", 301)
    if url.endswith(".html"):
        return redirect(url.rstrip(".html"), 301)

    if url.endswith(".png") or url.endswith(".xml") or url.endswith(".json") or url.endswith(".ico"):
        return send_from_directory("static", url)

    # actual code
    if url == "content":
        return redirect("/", 301)
    if exists("data/" + url.lstrip("/") + ".md"):
        filename = "data/" + url.lstrip("/") + ".md"
    else:
        filename = "data/404.md"

    return render_template("index.html",
                           content=Markup(markdown("".join(open(filename, encoding="UTF-8").readlines()),
                                                   use_file_vars=True,
                                                   extras=["use-file-vars", "tables"])))


@app.route("/archief/<string:url>")
def archief(url: str):
    if url == "content":
        return redirect("/")
    filename = ""
    ex = ""
    url, _ = splitext(url)
    print(url)

    for ext in file_exts:
        print("data/archief/" + url + ext)
        if exists("data/archief/" + url + ext):
            filename = "data/archief/" + url + ext
            ex = ext
            break
    if filename == "":
        filename = "data/404.md"
        ex = ".md"
    if ex == ".html":
        return Markup("".join(open("data/archief/" + url + ".html", encoding="utf-8").readlines()))
    elif ex == ".md":
        return render_template("index.html",
                               content=Markup(markdown("".join(open(filename, encoding="UTF-8").readlines()),
                                                       use_file_vars=True,
                                                       extras=["use-file-vars"])))
    elif ex == ".txt":
        return render_template("index.html", content="".join(open(filename, encoding="UTF-8").readlines()))
    elif ex == ".pdf":
        return send_file("data/archief/" + url + ".pdf", mimetype="application/pdf")
    else:
        return render_template("index.html", content="".join(open(filename, encoding="UTF-8").readlines()))


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5667)
