import os

from flask import (Blueprint, current_app, flash, jsonify, redirect, request,
                   send_from_directory, url_for)
from flask_cors import CORS, cross_origin
from werkzeug.utils import secure_filename

articles_api_bp = Blueprint(
    "articles", __name__, template_folder="templates")

cors = CORS(articles_api_bp, resources={
            r"/articles": {"origins": "http://localhost:5500"}})


@articles_api_bp.route("/<path:article>")
@cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
def send_text_file(article):
    return send_from_directory(directory="articles_files", path=article)


@articles_api_bp.route('/')
@cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
def index():
    # List files in articles directory
    files = list()
    for filename in os.listdir(os.path.join(
            current_app.root_path, "articles_files")):
        path = os.path.join(os.path.join(
            current_app.root_path, "articles_files"), filename)
        if os.path.isfile(path):
            files.append(filename)
    return jsonify(files)


@articles_api_bp.route("/upload", methods=("POST",))
@cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
def upload_file():
    if request.method == "POST":
        if "file" not in request.files:
            flash("No file part")
            return redirect(request.url)
        file = request.files["file"]
        if file.filename == '':
            flash("No selected file")
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(
                current_app.config["UPLOAD_FOLDER"], filename))
            return redirect(url_for("articles.send_text_file",
                                    article=filename))


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower(
           ) in current_app.config["ALLOWED_EXTENSIONS"]
