import ics2json
import time
from flask import Flask, request, jsonify


# rather dirty caching functionality
c = {}
def cache(f, url):
    if url not in c:
        c[url] = (time.time(),f(url))
    else:
        if time.time() - c[url][0] > 3600:
            c[url] = (time.time(),f(url))
    return c[url][1]


app = Flask("ics2json")

@app.route("/")
def parse():
    url = request.args.get("url")
    try:
        status = 200
        m_type = "application/json"
        cont = cache(ics2json.convert_url, url)
    except Exception:
        status = 500
        m_type = "text/plain"
        cont = "Please provide a valid .ics url"
    response = app.response_class(
            response=cont,
            status=status,
            mimetype=m_type,
            headers={'Access-Control-Allow-Origin':"*"}
    )
    return response
    

app.run(debug=False, port=8013)