import json

from flask import Flask, render_template, request
from db import load_file

app = Flask(__name__)

JSON_FILE = {}


@app.route("/add")
def add_releve():
    JSON_FILE = json.load(open("db.json", "r"))
    JSON_FILE['releves'].append(
        {
            "count": request.json['data']['uplink_message']['decoded_payload']['count'],
            "temp": request.json['data']['uplink_message']['decoded_payload']['temp'],
            "hygro": request.json['data']['uplink_message']['decoded_payload']['hygro']
        }
    )
    with open("db.json", "w") as file:
        json.dump(JSON_FILE, file)
    return "OK"


@app.route('/')
def hello_world():  # put application's code here
    JSON_FILE = json.load(open("db.json", "r"))
    releves = []
    for releve in JSON_FILE['releves']:
        new_releve = [releve['count'], releve['temp'], releve['hygro']]
        releves.append(new_releve)
    return render_template("index.html", list1=releves)


if __name__ == '__main__':
    app.run()
