from flask import Flask, render_template, request, abort, send_from_directory
import openai
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 class="centered"><source src="{}" type="video/{}"></video>"""

def preprocess_content(defs):
    md = defs.get("markdown", "")
    if md:
        content = markdown(md)
        content = RE_VID.sub(lambda m: TEMPLATE_VID.format(m.group(1), m.group(1).split('.')[-1]), content)
    else:
        content = ""
    img = defs.get("image", {})
    match img.get("placement", "none"):
        case "above":
            content = """<img src="{source}" alt="{alt}" class="centered w-{width}"/><br/>\n""".format(**img)+content
        case "left":
            content = """<img src="{source}" alt="{alt}" class="float-left w-{width}"/><br/>\n""".format(**img)+content
        case "right":
            content = """<img src="{source}" alt="{alt}" class="float-right w-{width}"/><br/>\n""".format(**img)+content
        case "below":
            content = content+"""<br/>\n<img src="{source}" alt="{alt}" class="centered w-{width}"/><br/>\n""".format(**img)
    if defs.get('soundtrack'):
        content = """<audio loop data-autoplay><source src="{}" type="audio/{}"></audio>\n""".format(
                      defs["soundtrack"], defs["soundtrack"].split(".")[-1])+content
    return content

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

load_dotenv()
openai.organization = "org-GFWgNyt7NSKpCv6GhzXYZTpi"

application = Flask(__name__)

@application.get("/")
def home():
    payload = json.load(open("static/slides.json"))
    preprocess_payload(payload)
    return render_template("slides.html", generate_indices=False, **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", "audio"]:
        choices = glob("static/media/{}/*.*".format(topic))
        titles = [os.path.basename(c) for c in choices]
        try:
            descdir = json.load(open("static/media/{}.json".format(topic)))
        except FileNotFoundError:
            descdir = {}
        return {
            "type": "string",
            "enum": choices,
            "options": {
                "enum_titles": [descdir.get(t, t.rsplit(".", 1)[0]) for t in titles]
            }
        }
    abort(404)

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

@application.route("/img", methods=['GET', 'POST'])
def image():
    if request.method=='GET':
        src = "static/img/marble-question-mark.png"
        alt = "A question mark"
        prompt = ""
    else:
        prompt = request.form["prompt"]
        alt = prompt
        response = openai.Image.create(prompt=prompt, n=1, size="1024x1024")
        src = response['data'][0]['url']
    return render_template("image.html", src=src, alt=alt, prompt=prompt)

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