import {useEffect, useState} from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import Diagramm from "./components/Diagramm.jsx";
import HistoryTable from "./components/HistoryTable.jsx";
import CurrentDataChart from "./components/CurrentDataChart.jsx";
import LivePreview from "./components/LivePreview.jsx";

/**
 * @component App
 * @description Root component of the frontend that manages state for sensor data,
 *              periodic data fetching, and rendering of different display components.
 * @returns {JSX.Element} The rendered main application container and visual charts.
 */
export default function App() {

    const [sensorData, setSensorData] = useState();
    const [allData, setAllData] = useState();

    /**
     * @hook useEffect
     * @description Automatically starts periodic data fetching on component mount.
     * Updates sensor, history, and regression data every second.
     * Cleans up by clearing the interval when unmounted.
     */
    useEffect(() => {
        getSensorData()
        getAllData()

        const interval = setInterval(() => {
            getSensorData()
            getAllData()
        }, 1000)

        return () => clearInterval(interval)
    }, [])


    /**
     * @function getSensorData
     * @description Fetches the latest live sensor reading from the backend API.
     * @returns {Promise<void>} Updates the `sensorData` state with the fetched JSON.
     */
    async function getSensorData() {
        console.log("calling getSensorData")
        const request = await fetch('http://172.16.111.32:8000/sensor')
        const data = await request.json()
        console.log("sensor data", data)
        setSensorData(data)
    }


    /**
     * @function getAllData
     * @description Fetches all stored historical sensor readings from the backend.
     * @returns {Promise<void>} Updates the `allData` state with the fetched dataset.
     */
    async function getAllData() {
        console.log("calling getAllData")
        const request = await fetch('http://172.16.111.32:8000/get/all')
        const data = await request.json()
        setAllData(data)
    }

    return (
        <div className={"container"}>
            <h1>Asia</h1>

            <CurrentDataChart sensorData={sensorData}/>

            <Diagramm data={allData}/>

            <HistoryTable allData={allData}/>

            <LivePreview />
        </div>
    )

}