#!/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)

valid_ranks = ['gold', 'silver', 'bronze']

app = Flask(__name__)

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

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

@app.route('/medals', methods=['POST'])
def add_medal():
    try:
        new = json.loads(request.data)
        if new['rank'] not in valid_ranks:
            return jsonify({"status": "error", "message": "The valid ranks are gold, silver and bronze"}), 400
        next_id = j[-1]['id']+1
        j.append({
            "id": next_id,
            "rank": new['rank'],
            "sportID": new['sportID'],
            "athleteID": new['athleteID']
        })
        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('/medals/<id>', methods=['GET'])
def get_medal(id):
    for m in j:
        print(m['id'])
        if m['id'] == int(id):
            return jsonify({"status": "success", "data": m})
    return jsonify({"status": "error", "message": "Id not found"}), 404 

@app.route('/medals/<id>', methods=['PATCH'])
def edit_medal(id):
    try:
        update = json.loads(request.data)
        entries = ['rank', 'sportID', 'athleteID']
        for i, m in enumerate(j):
            if m['id'] == int(id):
                for e in entries:
                    if update.get(e) is not None:
                        if e == "rank":
                            if update[e] not in valid_ranks:
                                return jsonify({"status": "error", "message": "The valid ranks are gold, silver and bronze"}), 400
                        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('/medals/<id>', methods=['DELETE'])
def  rm_medal(id):
    for i, m in enumerate(j):
        print(m['id'])
        if m['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)