import requests, json
from os import getenv
from flask import Flask, request, abort

# consts
metric_map = {
    "spots": "free_slots",
    "bikes": "avl_bikes",
    "capacity": "total_slots",
    "location": "coordinates"
}
url = "https://vancouver-ca.smoove.pro/api-public/stations"

#with open('live_dump.json') as f:
#    old_data = json.load(f)
#    data = old_data

def refresh_data():
    # try to get new data
    try:
        new = requests.get(url)
    except requests.exceptions.RequestException:
        print("failed to get data")
        data = None
    else:
        data = new.json()["result"]

# init libs
app = Flask(__name__)

# main function to get data from api
def get_bikes(station, metric):
    refresh_data()

    # if refresh failed, return 404
    if not data:
        return 502

    # find the station
    match = False
    for each in data:
        split = each['name'].split(' ', 1)
        id = split[0]
        name = split[1]
        if station == id or station == name:
            match = each
            break

    # return 404 if no match
    if not match:
        return 404

    if metric == "both":
        result = "Spots: " + str(match["avl_bikes"]) + '<br/>'
        result += "Bikes: " + str(match["free_slots"])
        return result
    return(str(match[metric]))

# interprets REST requests at a given location
# you can get /api/station/metric to get just one metric w/o formatting
@app.route('/api/<string:station>/<string:metric>', methods=['GET'])
def get_metric_info(station, metric):
    try:
      metric_map[metric]
    except KeyError:
        abort(404, description="Sorry, that metric does not exist")
    result = get_bikes(station, metric_map[metric])
    if result == 404:
        abort(404, description="Sorry, that station does not exist")
    elif result == 502:
        abort(502, description="Sorry, the API server isn't responding right now")
    else:
        return result

# interprets REST requests at a given location
# get /api/station (can be a number or name) returns bikes+slots available
@app.route('/api/<string:station>/', methods=['GET'])
def get_station_info(station):
    result = get_bikes(station, "both")
    if result == 404:
        abort(404, description="Sorry, that station does not exist")
    elif result == 502:
        abort(502, description="Sorry, the API server isn't responding right now")
    else:
        return result
