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

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

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

    useEffect(() => {
        if (dev === null || dev === undefined) {
            return;
        }
        axiosGet("/records", {
            device: dev?.id,
            measurement: measurement,
            range: range
        }).then((res) => {
            const fetchedTS = res.data;
            fetchedTS.data = fetchedTS.data.map((val) => getPPFD(val));

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

    /**
     * Converts raw light data to PPFD value
     * @param strValue Light value F1;F2;..;F8
     * @returns {number} PPFD value
     */
    const getPPFD = (strValue) => {
        const values = strValue.split(';').map((val) => Number(val));
        //(cited in thesis) values are from https://www.researchgate.net/publication/351584740_A_Novel_Approach_to_Obtain_PAR_with_a_Multi-Channel_Spectral_Microsensor_Suitable_for_Sensor_Node_Integration
        let ppfd = -4.94265 //-9.8853/2
            + values[0] * 0.0023 //0.0046/2
            + values[1] * 0.0068 //0.0136/2
            + values[2] * 0.01215 //0.0243/2
            + values[3] * 0.02295 //0.0459/2
            - values[4] * 0.02355 //0.0471/2
            + values[5] * 0.00975 //0.0195/2
            + values[6] * 0.0089 //0.0178/2
            - values[7] * 0.0013 //0.0026/2
        return Math.max(ppfd, 0);
    }

    return (<>
        <ChartComponent title={display}
                        data={[timeSeries]}
                        lineColor={[color]}
                        label={[display]}
                        isPercent={false}
        />
    </>);
}

export default DeviceLightChart