from datetime import datetime
import os
from pathlib import Path

from flask import Flask, flash, request, redirect, render_template

from app.text_data import get_text_from_uid, is_valid_uid


UPLOAD_FOLDER = "files"

app = Flask(__name__)
app.config.from_pyfile("config/develop.py")


@app.route("/")
def root():
    app.logger.info("static path is " + app.static_url_path)
    app.logger.info("files will be uploaded to " + app.config["UPLOAD_FOLDER"])
    return app.send_static_file("index.html")


def bad_key():
    return "<h1>Key not recognized</h1>"


@app.route("/record-audio", methods=["POST", "GET"])
def record_audio():
    key = request.args.get("key")
    app.logger.info(f"key is `{key}`")
    if is_valid_uid(key):
        app.logger.info(f"found valid key `{key}`")
        text_to_speak = get_text_from_uid(key)
        if not text_to_speak:
            raise RuntimeError("This should never happen!")
        data = {"text_to_speak": text_to_speak, "text_uid": key}
        return render_template("recorder.html", data=data)
    #        return send_from_directory("static", "recorder.html")
    else:
        app.logger.info(f"found invalid key `{key}`")
        return bad_key()


@app.route("/save-record", methods=["POST"])
def save_record():
    # check if the post request has the file part
    # import ipdb; ipdb.set_trace()
    if "audio_data" not in request.files:
        flash("No file part")
        return redirect(request.url)
    text_uid = request.form.get("text_uid")
    if text_uid is None:
        return redirect(request.url)  # FIXME need better error handling
    audio_file = request.files["audio_data"]
    app.logger.info(f"File `{audio_file}`, uuid `{text_uid}` found.")
    # if user does not select file, browser also
    # submit an empty part without filename
    if audio_file.filename == "":
        flash("No selected file")
        return redirect(request.url)
    else:
        print(audio_file.filename)

    date_str = datetime.utcnow().isoformat()[:21]  # to the tenth of a second
    filename = f"{text_uid}_{date_str}.mp3"
    full_file_name = os.path.join(app.config["UPLOAD_FOLDER"], filename)
    app.logger.info(f"saving file to {full_file_name}")
    audio_file.save(full_file_name)
    return "<h1>Success</h1>"


if __name__ == "__main__":
    Path(app.config["UPLOAD_FOLDER"]).mkdir(parents=True, exist_ok=True)
    app.run(debug=True)
