from flask import Flask, send_from_directory, request
import os
import configuration

models = configuration.models
db = configuration.db
app = Flask(__name__)


###############################################################################
# SVELTE 'STATIC' BACKEND. Always send index.html and the requested js-files. (compiled by npm)

@app.route("/") #index.html
def index():
    return send_from_directory('../client/public', 'index.html')
@app.route("/<path:path>") #js-files
def js(path):
    return send_from_directory('../client/public', path)
@app.route("/app/containerdata/files/<path:path>")
def static_pdf(path):
    return send_from_directory('/app/containerdata/files/', path)



###############################################################################
# (simple) API for news_check.

@app.route("/api/article/<int:id>/get")
def get_article_by_id(id):
    with db:
        article = models.ArticleDownload.get_by_id(id)
        return article.to_dict()

@app.route("/api/article/first")
def get_article_first(min_id=0):
    with db:
        article = models.ArticleDownload.select(models.ArticleDownload.id).where(
            (models.ArticleDownload.verified == 0) &
            (models.ArticleDownload.id > min_id) &
            (models.ArticleDownload.archived_by == os.getenv("UNAME"))
            ).order_by(models.ArticleDownload.id).first()
        return {"id" : article.id}

@app.route("/api/article/<int:id>/next")
def get_article_next(id):
    with db:
        if models.ArticleDownload.get_by_id(id + 1).verified == 0:
            return {"id" : id + 1}
        else:
            return get_article_first(min_id=id) # if the current article was skipped, but the +1 is already verified, get_first will return the same article again. so specify min id.



@app.route("/api/article/<int:id>/set", methods=['POST'])
def set_article(id):
    json = request.get_json(silent=True) # do not raise 400 if there is no json!
    # no json usually means a file was uploaded
    if json is None:
        print("Detected likely file upload.")
        action = None
    else:
        action = request.json.get('action', None) # action inside the json might still be empty

    with db:
        article = models.ArticleDownload.get_by_id(id)
        if action:
            if action  == "a":
                article.verified = 1
            elif action == "b":
                article.verified = -1
        else: # implicitly action == "r":
            # request.files is an immutable dict
            file = request.files.get("file", None)
            if file is None: # upload tends to crash
                return "No file uploaded", 400

            artname, _ = os.path.splitext(article.file_name)
            fname =  f"{artname} -- related_{article.related.count() + 1}.{file.filename.split('.')[-1]}"
            fpath = os.path.join(article.save_path, fname)
            print(f"Saving file to {fpath}")
            file.save(fpath)
            article.set_related([fname])
            return {"file_path": fpath}

        article.save()
    return "ok"




if __name__ == "__main__":
    debug = os.getenv("DEBUG", "false") == "true"
    app.run(host="0.0.0.0", port="80", debug=debug)