import json

from flask import abort, request, session

from src.internals.database.database import get_cursor
from src.pages.api.v1 import v1api_bp
from src.types.account.account import Account
from src.utils.decorators import require_login


@v1api_bp.route("/shares/upload", methods=["POST"])
@require_login
def upload_share(user: Account):
    return ""  # uploads disabled
    if user.role not in ["administrator", "moderator", "uploader"]:
        return abort(403)

    service = request.form.get("service", None)
    user = request.form.get("user", None)
    uploads = json.loads(request.form["uppyResult"])
    model = dict(
        name=request.form.get("title"),
        description=request.form.get("content", ""),
        uploader=session.get("account_id"),
    )
    query = """
        INSERT INTO shares ({fields})
        VALUES ({values})
        RETURNING *
    """.format(
        fields=",".join(model.keys()), values=",".join(["%s"] * len(model.values()))
    )
    cursor = get_cursor()
    cursor.execute(query, list(model.values()))
    returned = cursor.fetchone()
    share_id = returned["id"]
    for upload in uploads:
        for u in upload["successful"]:
            file_rel = dict(
                upload_id=u["tus"]["uploadUrl"].split("/files/")[-1],
                upload_url=u["tus"]["uploadUrl"],
                filename=u["name"],
                share_id=share_id,
            )
            get_cursor().execute(
                """
                INSERT INTO file_share_relationships ({fields})
                VALUES ({values})
            """.format(
                    fields=",".join(file_rel.keys()),
                    values=",".join(["%s"] * len(file_rel.values())),
                ),
                list(file_rel.values()),
            )

            lookup_rel = dict(share_id=share_id, service=service, user_id=user)
            get_cursor().execute(
                """
                INSERT INTO lookup_share_relationships ({fields})
                VALUES ({values})
            """.format(
                    fields=",".join(lookup_rel.keys()),
                    values=",".join(["%s"] * len(lookup_rel.values())),
                ),
                list(lookup_rel.values()),
            )

    # This should redirect to the share
    return "", 200
