from flask import Flask, render_template, request, abort, send_from_directory
from dotenv import load_dotenv
from markdown import markdown
from glob import glob
import json
import os
import sys
import time
import shutil
import re

RE_VID = re.compile("""\[video ["']([^['"]*?)["']\]""")
TEMPLATE_VID = """<video controls><source src="{}" type="video/{}"></video>"""

RE_SOUNDTRACK = re.compile("""\[soundtrack ["']([^['"]*?)["']\]""")
TEMPLATE_SOUNDTRACK = """<audio data-autoplay><source src="{}" type="audio/{}"></audio>"""

def preprocess_markdown(md):
    if md:
        content = markdown(md)
        content = RE_VID.sub(lambda m: TEMPLATE_VID.format(m.group(1), m.group(1).split('.')[-1]), content)
        content = RE_SOUNDTRACK.sub(lambda m: TEMPLATE_SOUNDTRACK.format(m.group(1), m.group(1).split('.')[-1]), content)
        return content
    return ""

def preprocess_payload(payload):
    for column in payload.get("columns", []):
        column["content"] = preprocess_markdown(column.get("markdown"))
        for slide in column.get("slides", []):
            slide["content"] = preprocess_markdown(slide.get("markdown"))

load_dotenv()

application = Flask(__name__)

@application.get("/")
def home():
    payload = json.load(open("static/slides.json"))
    preprocess_payload(payload)
    return render_template("slides.html", **payload)

@application.post("/update")
def update():
    shutil.copy(
        "static/slides.json",
        time.strftime(
            "archive/slides-%Y-%m-%d-%H.%M.%S.json",
            time.localtime()))
    payload = request.get_json()
    print(type(payload))
    json.dump(payload, sys.stdout, indent=4)
    json.dump(payload, open("static/slides.json", "w"), indent=4)
    return({"status": "success"})

@application.get("/enum/<topic>")
def choices(topic):
    if topic in ["img", "bg", "bg-video"]:
        return {"type": "string", "enum": glob("static/{}/*.*".format(topic))}
    abort(404)

@application.get("/schema.json")
def schema():
    return render_template("slides.schema.json", backgrounds=choices("bg"))

@application.get("/editor")
def editor():
    return render_template("editor.html")

@application.route("/favicon.ico")
def favicon():
    return send_from_directory(os.path.join(application.root_path, "static"),
                               "favicon.ico", mimetype="image/vnd.microsoft.icon")
