from flask import Blueprint, request, jsonify
from ..model.sensors import iot_data, set_iot_data, save_data
import os, json

# TODO: create a Blueprint + routes for 'api/iot' endpoint
iot_api = Blueprint("iot_api", __name__)

DATA_FILE = "/home/nedi/iap1-labs/lab4/iot_data.json"

@iot_api.route("/api/iot", methods=["GET"])
def get_sensor_data():
    return jsonify(iot_data)

@iot_api.route("/api/iot", methods=["POST"])
def update_sensor_data():
    payload = request.get_json(silent=True)

    set_iot_data(payload)

    save_data(DATA_FILE)
    return jsonify(iot_data)

@iot_api.route("/api/iot", methods=["DELETE"])
def reset_sensor_data():
    for key in iot_data:
        iot_data[key] = 0
    save_data(DATA_FILE)
    return jsonify(iot_data)