from flask import render_template, Response, request, Blueprint

from helpers.flask_response import basic_msg, basic_msg_html
from helpers.disk_file_versioning import DiskFileVersioning
from template_pwndoc import TNSTemplatePwndoc
from template_manager import PwndocTemplateManager
from helpers.template_grouping import TemplateGrouping
from typing import List
from loguru import logger

bp = Blueprint('api_root', __name__, template_folder='templates')


@bp.route("")
@bp.route("/")
def homepage():
    return render_template('base.html')


@bp.route("/json_editor", methods=["GET"])
def json_editor():
    PwndocTemplateManager.update_template_db_from_pwndoc()
    files_selector = [(x, x) for x in DiskFileVersioning().list_available_files()]
    templates: List[TNSTemplatePwndoc] = PwndocTemplateManager.get_all_templates()
    templates.sort(key=lambda x: x.fid)
    return render_template("json_editor.html", files=files_selector, templates=templates)


@bp.route("/json_diff", methods=["GET"])
def json_diff():
    return render_template("json_diff_standalone.html")


@bp.route("/versioned_file/<filename>", methods=["GET"])
def get_versioned_file(filename: str):
    file_content = DiskFileVersioning().get_file_from_disk(filename)
    if file_content is None:
        return basic_msg("Filename doesn't match existing mapping"), 404
    return Response(file_content, mimetype='application/json')  # todo: this might not have to be JSON


@bp.route("/versioned_file/<filename>", methods=["POST"])
def upload_versioned_file(filename: str):
    data = request.data

    file_content = DiskFileVersioning().save_file_to_disk(filename, data.decode())
    if file_content is None:
        return basic_msg("Filename doesn't match existing mapping"), 404

    if filename == 'groups':
        TemplateGrouping.add_new_gids()
    return basic_msg("OK")
