package src

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
)

type EnvironmentData struct {
	Temp     float64 `json:"t" binding:"required"`
	Humidity float64 `json:"h" binding:"required"`
}

func CreateData(c *gin.Context) {
	var data EnvironmentData
	if err := c.ShouldBindJSON(&data); err != nil {
		println(err.Error())
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	} else {
		doc := data.toBSONOld()
		fmt.Printf("T:%f H:%f\n", data.Temp, data.Humidity)
		_, err := dbCollection.InsertOne(context.TODO(), doc)

		if err != nil {
			println(err.Error())
			c.JSON(http.StatusInternalServerError, "")
		} else {
			c.JSON(http.StatusOK, "")
		}
	}
}
func CreateEnvironmentData(c *gin.Context) {
	var data EnvironmentData
	if err := c.ShouldBindJSON(&data); err != nil {
		println(err.Error())
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	} else {
		uintID, err := strconv.ParseUint(c.Param("id"), 10, 64)
		if err != nil {
			c.JSON(http.StatusNotFound, "")
		} else {
			doc := data.toBSON(uintID)
			fmt.Printf("T:%f H:%f\n", data.Temp, data.Humidity)
			_, err := dbCollection.InsertOne(context.TODO(), doc)
			if err != nil {
				println(err.Error())
				c.JSON(http.StatusInternalServerError, "")
			} else {
				c.JSON(http.StatusOK, "")
			}
		}
	}
}

func (data *EnvironmentData) toBSON(id uint64) bson.M {
	fmt.Printf("%d", id)
	return bson.M{"Temperature": data.Temp,
		"Humidity": data.Humidity,
		"ApiID":    int64(id),
		"Time":     time.Now().UTC(),
	}
}

func (data *EnvironmentData) toBSONOld() bson.M {

	return bson.M{"Temperature": data.Temp,
		"Humidity": data.Humidity,
		"Time":     time.Now().UTC(),
	}
}
