from flask import Flask, send_from_directory, request
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():
    with db:
        article = models.ArticleDownload.select(models.ArticleDownload.id).where(models.ArticleDownload.verified == 0).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()



@app.route("/api/article/<int:id>/set", methods=['POST'])
def set_article(id):
    action = request.json['action']
    with db:
        article = models.ArticleDownload.get_by_id(id)
        if action == "a":
            article.verified = 1
        elif action == "b":
            article.verified = -1
        elif action == "r":
            article.set_related()
        article.save()
        return "ok"





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