from flask import Flask, jsonify, request
from pathlib import Path
import json
from models import Discipline, ListeDiscipline
# noinspection PyUnresolvedReferences
from flask_swagger_ui import get_swaggerui_blueprint
import os

app = Flask(__name__)
app.config['DISCIPLINE_FILE'] = os.getenv('DISCIPLINE_FILE', Path(__file__).parent.parent / 'data' / 'disciplines.json')
print(app.config['DISCIPLINE_FILE'])

@app.route('/ping', methods=["GET"])
def ping():
    return jsonify({"message": "pong"}), 200

@app.route('/', methods=["GET"])
def listeDiscipline():
    """
    Renvoie la liste des disciplines
    """
    # Offset / Limit
    offset = request.args.get('offset', 0)
    limit = request.args.get('limit', 10)
    listeDisciplines = ListeDiscipline()
    listeDisciplines.loadFromJson(app.config['DISCIPLINE_FILE'])

    if limit != 0:
        listeDisciplines.root = listeDisciplines.root[int(offset):int(offset)+int(limit)]
    else:
        listeDisciplines.root = listeDisciplines.root[int(offset):]

    return jsonify(listeDisciplines.model_dump()), 200

@app.route('/<int:id>', methods=["GET"])
def getDiscipline(id: int):
    """
    Renvoie une discipline par son id
    """
    listeDisciplines = ListeDiscipline()
    listeDisciplines.loadFromJson(app.config['DISCIPLINE_FILE'])
    for discipline in listeDisciplines.root:
        if discipline.id == id:
            return jsonify(discipline.model_dump()), 200
    return jsonify({"message": "Discipline introuvable"}), 404

@app.route('/<int:id>', methods=["DELETE"])
def deleteDiscipline(id: int):
    """
    Supprime une discipline par son id
    """
    listeDisciplines = ListeDiscipline()
    listeDisciplines.loadFromJson(app.config['DISCIPLINE_FILE'])
    for discipline in listeDisciplines.root:
        if discipline.id == id:
            listeDisciplines.root.remove(discipline)
            with open(app.config['DISCIPLINE_FILE'], 'w') as f:
                json.dump(listeDisciplines.model_dump(), f, indent=4)
            return jsonify({"message": "Discipline supprimé"}), 200
    return jsonify({"message": "Discipline introuvable"}), 404

@app.route('/<int:id>', methods=["PUT"])
def updateDiscipline(id: int):
    """
    Met à jour une discipline par son id
    """
    listeDisciplines = ListeDiscipline()
    listeDisciplines.loadFromJson(app.config['DISCIPLINE_FILE'])
    for discipline in listeDisciplines.root:
        if discipline.id == id:
            data = json.loads(request.data)
            for key, value in data.items():
                setattr(discipline, key, value)
            with open(app.config['DISCIPLINE_FILE'], 'w') as f:
                json.dump(listeDisciplines.model_dump(), f, indent=4)
            return jsonify({"message": "Discipline mise à jour"}), 200
    return jsonify({"message": "Discipline introuvable"}), 404

@app.route('/<int:id>', methods=["PATCH"])
def patchDiscipline(id: int):
    """
    Met à jour une discipline par son id
    """
    listeDisciplines = ListeDiscipline()
    listeDisciplines.loadFromJson(app.config['DISCIPLINE_FILE'])
    for discipline in listeDisciplines.root:
        if discipline.id == id:
            data = json.loads(request.data)
            data["id"] = discipline.id # On ne peut pas changer l'id
            for key, value in data.items():
                if hasattr(discipline, key):
                    setattr(discipline, key, value)
            with open(app.config['DISCIPLINE_FILE'], 'w') as f:
                json.dump(listeDisciplines.model_dump(), f, indent=4)
            return jsonify({"message": "Discipline mis à jour"}), 200
    return jsonify({"message": "Discipline introuvable"}), 404

@app.route('/', methods=["POST"])
def addDiscipline():
    """
    Ajoute une discipline
    """
    listeDisciplines = ListeDiscipline()
    listeDisciplines.loadFromJson(app.config['DISCIPLINE_FILE'])
    discipline = Discipline(**json.loads(request.data))
    discipline.id = max([discipline.id for discipline in listeDisciplines.root]) + 1
    listeDisciplines.root.append(discipline)
    with open(app.config['DISCIPLINE_FILE'], 'w') as f:
        json.dump(listeDisciplines.model_dump(), f, indent=4)
    return jsonify(discipline.model_dump()), 200

swaggerui_blueprint = get_swaggerui_blueprint(
    "/swagger/",
    "/disciplines/static/swagger.yaml"
)
app.register_blueprint(swaggerui_blueprint)

def create_app():
    return app

if __name__ == '__main__':
    app.run()
