from flask import Flask, jsonify, request
from pathlib import Path
import json
from athlete import ListeAthlete, Athlete
# noinspection PyUnresolvedReferences
from flask_swagger_ui import get_swaggerui_blueprint
import os

app = Flask(__name__)
app.config['ATHLETE_FILE'] = os.getenv('ATHLETE_FILE', Path(__file__).parent.parent / 'data' / 'athletes.json')
@app.route('/ping', methods=["GET"])
def ping():
    return jsonify({"message": "pong"}), 200
@app.route('/', methods=["GET"])
def listeAthlete():
    """
    Renvoie la liste des athlètes
    """
    # Offset / Limit
    offset = request.args.get('offset', 0)
    limit = request.args.get('limit', 10)
    listeAthletes = ListeAthlete()
    listeAthletes.loadFromJson(app.config['ATHLETE_FILE'])

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

    return jsonify(listeAthletes.model_dump()), 200

@app.route('/<int:id>', methods=["GET"])
def getAthlete(id: int):
    """
    Renvoie un athlète par son id
    """
    listeAthletes = ListeAthlete()
    listeAthletes.loadFromJson(app.config['ATHLETE_FILE'])
    for athlete in listeAthletes.root:
        if athlete.id == id:
            return jsonify(athlete.model_dump()), 200
    return jsonify({"message": "Athlete introuvable"}), 404
@app.route('/<int:id>', methods=["DELETE"])
def deleteAthlete(id: int):
    """
    Supprime un athlète par son id
    """
    listeAthletes = ListeAthlete()
    listeAthletes.loadFromJson(app.config['ATHLETE_FILE'])
    for athlete in listeAthletes.root:
        if athlete.id == id:
            listeAthletes.root.remove(athlete)
            with open(app.config['ATHLETE_FILE'], 'w') as f:
                json.dump(listeAthletes.model_dump(), f, indent=4)
            return jsonify({"message": "Athlete supprimé"}), 200
    return jsonify({"message": "Athlete introuvable"}), 404

@app.route('/<int:id>', methods=["PUT"])
def updateAthlete(id: int):
    """
    Met à jour un athlète par son id
    """
    listeAthletes = ListeAthlete()
    listeAthletes.loadFromJson(app.config['ATHLETE_FILE'])
    for athlete in listeAthletes.root:
        if athlete.id == id:
            data = json.loads(request.data)
            for key, value in data.items():
                setattr(athlete, key, value)
            with open(app.config['ATHLETE_FILE'], 'w') as f:
                json.dump(listeAthletes.model_dump(), f, indent=4)
            return jsonify({"message": "Athlete mis à jour"}), 200
    return jsonify({"message": "Athlete introuvable"}), 404

@app.route('/<int:id>', methods=["PATCH"])
def patchAthlete(id: int):
    """
    Met à jour un athlète par son id
    """
    listeAthletes = ListeAthlete()
    listeAthletes.loadFromJson(app.config['ATHLETE_FILE'])
    for athlete in listeAthletes.root:
        if athlete.id == id:
            data = json.loads(request.data)
            data["id"] = athlete.id # On ne peut pas changer l'id
            for key, value in data.items():
                if hasattr(athlete, key):
                    setattr(athlete, key, value)
            with open(app.config['ATHLETE_FILE'], 'w') as f:
                json.dump(listeAthletes.model_dump(), f, indent=4)
            return jsonify({"message": "Athlete mis à jour"}), 200
    return jsonify({"message": "Athlete introuvable"}), 404

@app.route('/', methods=["POST"])
def addAthlete():
    """
    Ajoute un athlète
    """
    listeAthletes = ListeAthlete()
    listeAthletes.loadFromJson(app.config['ATHLETE_FILE'])
    athlete = Athlete(**json.loads(request.data))
    athlete.id = max([athlete.id for athlete in listeAthletes.root]) + 1
    listeAthletes.root.append(athlete)
    with open(app.config['ATHLETE_FILE'], 'w') as f:
        json.dump(listeAthletes.model_dump(), f, indent=4)
    return jsonify(athlete.model_dump()), 200

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

def create_app():
    return app

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