/**
 * @file DeviceLightChart.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

import {useEffect, useState} from "react";
import {axiosGet} from "../../services/AxiosService";
import BarChartComponent from "./BarChartComponent";

function DeviceLightChart(props) {
    const dev = props.device;
    const range = props.range || "-1h";
    const display = props.chartData.display;
    const measurement = props.chartData.measurement;
    const [timeSeries, setTimeSeries] = useState([]);

    useEffect(() => {
        if (dev === null || dev === undefined) {
            return;
        }
        axiosGet("/records", {
            device: dev?.id,
            measurement: measurement,
            range: range
        }).then((res) => {
            //need to transform data to multiple datasets in one chart
            const lightSeries = [];
            const dataList = res.data.data;
            dataList.forEach((str, i, arr) => {
                arr[i] = str.split(';');
            });

            for (let color = 0; color < 8; ++color) {
                let dataSetData = [];
                for (let day = 0; day < dataList.length; ++day) {
                    dataSetData.push(dataList[day][color]);
                }

                lightSeries.push({
                    "legend": res.data.legend,
                    "data": dataSetData
                });
            }

            setTimeSeries(lightSeries);
            console.log("Dev: " + dev?.name + " > " + res.data.data);
        }).catch((e)=>{
            console.log("ERROR: " + e);
        });
    }, [dev, range, measurement]);

    return (<>
        <BarChartComponent title={display}
                         data={timeSeries}
                         color={["rgb(115,0,255)",
                             "rgb(0,21,255)",
                             "rgb(0,217,255)",
                             "rgb(0,255,89)",
                             "rgb(153,255,0)",
                             "rgb(255,166,0)",
                             "rgb(255,47,0)",
                             "rgb(255,0,0)",
                         ]}
                         label={["410nm", "440nm", "480nm", "510nm", "555nm", "590nm", "630nm", "680nm"]}
        />
    </>);
}

export default DeviceLightChart