import logging

from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from median.models import ListeErrorModel

from common.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from median.constant import TypeListe
import html


list_blueprint = Blueprint("list", __name__)

logger = logging.getLogger("median")


@list_blueprint.route("note/<string:list_name>", methods=["GET"])
@jwt_required()
def get_list_note(list_name):
    list_message: ListeErrorModel = ListeErrorModel.get_or_none(ListeErrorModel.liste == list_name)

    if list_message:
        decoded_message = html.unescape(list_message.message) if list_message.message else list_message.message
        return {"message": decoded_message}

    return {}, HTTP_200_OK


@list_blueprint.route("note/<string:list_name>", methods=["PUT"])
@jwt_required()
def create_update_list_note(list_name):
    data = request.json

    if not data or "mode" not in data or "message" not in data:
        return {"error": "Missing required fields: mode, message"}, HTTP_400_BAD_REQUEST

    mode = data["mode"]
    message = html.escape(data["message"]) if data["message"] else data["message"]

    if mode not in [item.value for item in TypeListe]:
        return {"error": f"Invalid mode used. mode given : [{mode}]"}, HTTP_400_BAD_REQUEST

    try:
        list_message: ListeErrorModel = ListeErrorModel.get_or_none(
            (ListeErrorModel.liste == list_name) & (ListeErrorModel.mode == mode)
        )

        # If message is empty and instance exists, delete it. Check also if it contains "<br>" (escaped)
        # This empty line comes from the Quasar WYSIWYG editor
        if list_message and (not message or message == "" or message == html.escape("<br>")):
            list_message.delete_instance()
            return {"message": "List note deleted successfully"}, HTTP_200_OK

        # If message has content, update or create instance
        elif message:
            if list_message:
                list_message.message = message
                list_message.save()
                return {"message": "List note updated successfully"}, HTTP_200_OK
            else:
                ListeErrorModel.create(liste=list_name, mode=mode, message=message)
                return {"message": "List note created successfully"}, HTTP_200_OK

        return {"message": "No action performed"}, HTTP_200_OK

    except Exception as e:
        logger.error(f"Error managing list note: {str(e)}")
        return {"error": str(e)}, HTTP_400_BAD_REQUEST
