#include "thermaldatarenderer.h"
#include "imagemaster.h"
#include <chrono>
void ThermalDataRenderer::receiveNewData(QVector<float> data) {
    auto start = std::chrono::high_resolution_clock::now();
    //fprintf(stderr, "in renderer");
    //fprintf(stderr, "renderer received data of length: %d\n",data.length());

    if(activeAttributer >= attributers.size()){
        fprintf(stderr, "attr size mismatch: %d; %d",activeAttributer,attributers.size());
        activeAttributer = 0;
    }

    if(renderBuffer.size() < data.size())
        renderBuffer = QVector<QColor>(data.size()+1);

    QVector<float> sortedData = data;
    std::sort(sortedData.begin(), sortedData.end());

    const float lowerPercentile = lp/100.0f;
    const float upperPercentile = hp/100.0f;

    int lowerIndex = static_cast<int>(lowerPercentile * sortedData.size());
    int upperIndex = static_cast<int>(upperPercentile * sortedData.size());

    minValue = sortedData[lowerIndex];
    maxValue = sortedData[upperIndex];

    //fprintf(stderr, "minValue: %f\t", minValue);
    //fprintf(stderr, "maxValue: %f\n", maxValue);

    attributers[activeAttributer]->maxValue = maxValue;
    attributers[activeAttributer]->minValue= minValue;


    for (int i = 0; i < data.size() && i < renderBuffer.size(); ++i) {
        renderBuffer[i] = attributers[activeAttributer]->encode(data[i]);
    }

    if(takeCapture){
        saveImageFromColorArray(renderBuffer, 32, 24, 5); //5 times upscale from 32x24 to 160x120
        takeCapture = false;
    }

    emit dataChanged();
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    //fprintf(stderr,"renderer time: %lld\n",elapsed);
}
