#!/usr/bin/env python
# encoding: utf-8
import os
import json
from flask import Flask, request, jsonify

file = 'data/'+os.path.splitext(os.path.basename(__file__))[0]+'.json'


with open(file, 'r') as f:
    j = json.load(f)

def save_json(new_json):
    with open(file, 'w') as f:
        f.write(json.dumps(new_json, indent=4))
    with open(file, 'r') as f:
        j = json.load(f)

app = Flask(__name__)

@app.route('/healthcheck', methods=['GET'])
def ping():
    return jsonify({"conatiner_status": "healthy"})

@app.route('/athletes', methods=['GET'])
def list_athletes():
    return jsonify({"status": "success", "data": j})

@app.route('/athletes', methods=['POST'])
def add_athlete():
    try:
        new = json.loads(request.data)
        next_id = j[-1]['id']+1
        j.append({
            "id": next_id,
            "name": new['name'],
            "surname": new['surname'],
            "email": new['email'],
            "country": new['country'],
            "isDisabled": new['isDisabled']
        })
        save_json(j)
        return jsonify({"status": "success", "id": next_id})
    except Exception as e:
        print(e)
        return jsonify({"status": "error", "message": "Please provide a valid JSON"}), 500

@app.route('/athletes/<id>', methods=['GET'])
def get_athlete(id):
    for a in j:
        print(a['id'])
        if a['id'] == int(id):
            return jsonify({"status": "success", "data": a})
    return jsonify({"status": "error", "message": "Id not found"}), 404 

@app.route('/athletes/<id>', methods=['PATCH'])
def edit_athlete(id):
    try:
        update = json.loads(request.data)
        entries = ['name', 'surname', 'email', 'country', 'isDisabled']
        for i, a in enumerate(j):
            if a['id'] == int(id):
                for e in entries:
                    if update.get(e) is not None:
                        j[i][e] = update[e]
                save_json(j)
                return jsonify({"status": "success"})
        return jsonify({"status": "error", "message": "Id not found"}), 404 
    except Exception as e:
        print(e)
        return jsonify({"status": "error", "message": "Please provide a valid JSON"}), 500

@app.route('/athletes/<id>', methods=['DELETE'])
def  rm_athlete(id):
    for i, a in enumerate(j):
        print(a['id'])
        if a['id'] == int(id):
            j.pop(i)
            save_json(j)
            return jsonify({"status": "success"})
    return jsonify({"status": "error", "message": "Id not found"}), 404 


app.run(host="0.0.0.0", debug=False)