from pymongo import MongoClient
from flask import Flask, request
from pprint import pprint
import time 

app = Flask(__name__)

client = MongoClient("sedatabase", 27017)
db = client["react_database"]
user = db["user"]
location = db["location"]


@app.route("/report-location", methods=["PUT"])
def report_location():
    gpsData = request.json
    location.insert_one(gpsData)
    
    return ('', 204)

@app.route("/users", methods=["GET"])
def get_users():
    
    pipeline = [
        { "$sort": { "name": 1, "timestamp": -1 } },
        { "$group": {
            "_id": "$name",
            "timestamp": { "$first": "$timestamp" },
            "longitude": { "$first": "$longitude" },
            "latitude": { "$first": "$latitude" }
        }}
    ]
    
    lastLocations = list(location.aggregate(pipeline))

    users = list(user.find({}, {'_id': False}))
    for u in users:
        for userLoc in lastLocations:
            if u["name"]==userLoc["_id"]:
                u.update(userLoc)
        if "longitude" not in u:
            u["longitude"] = None
        if "latitude" not in u:
            u["latitude"] = None
        
        u["online"] = "timestamp" in u and (time.time() - u["timestamp"])<30
    
    return {"users": users}

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response


if __name__=="__main__":
    if user.find().count()<3:
        user.insert_many([
            {
              "shortName": "VEN",
              "fullName": "Martin Venzl",
              "name": "Martin",
              "color": "#ddd",
            },
            {
              "name": "Simon",
              "fullName": "Simon Ellinger",
              "shortName": "ELL",
              "color": "#ffff00"
            },
            {
              "name": "Lukas",
              "fullName": "Lukas Wagner",
              "shortName": "WAG",
              "color": "#00ff00"
            },
            {
              "name": "Bernie",
              "fullName": "Bernadette Hammerle",
              "shortName": "HAM",
              "color": "#888822"
            }
        ])
    
    app.run(host='0.0.0.0')
