#include "specgramViewWidget.h"
#include <QImage>
#include <QPaintEvent>
#include <QPainter>
#include <QPen>

#include "matching/matching.h"

void specgramViewWidget::paintEvent(QPaintEvent *e)
{
    if(!image){return;}  // ここは結構あむない．
    QPainter painter(this);
    painter.drawImage(0, 0, *image);
}

void specgramViewWidget::setSpecgram(analysisWindow::specgram *spec, analysisWindow::specgram *dstSpec)
{
    this->spec = spec;
    this->dstSpec = dstSpec;
    maxSpecValue = 1.0e-12;
    for(int i = 0; i < spec->timeLength; i++){
        for(int j = 0; j < spec->fftLength; j++){
            if(maxSpecValue < spec->spec[i][j]){ maxSpecValue = spec->spec[i][j]; }
        }
    }
    minSpecValue = maxSpecValue * 1.0e-5; // 表示域
    this->resize(spec->timeLength * this->scale, height());
    this->parent->resize(this->width(), this->parent->height());
    delete image;
    image = new QImage(width(), height(), QImage::Format_ARGB32 );

    for(int i = 0; i < image->width(); i++){
        int index = i * scale;
        if(index < 0){index = 0;}
        if(index >= spec->timeLength){index = spec->timeLength - 1;}
        for(int j = 0; j < image->height(); j++){
            double color, dstColor;
            int c, dstC;
            double y = (double)spec->fftLength / 2.0 * (double)(height() - j) / (double)height();
            if(y < 0){y = 0.0;}
            if(y > spec->fftLength / 2){y = spec->fftLength / 2;}
            color = interpolateArray(y, spec->spec[index]);
            dstColor = interpolateArray(y, dstSpec->spec[index]);
            color = (log(color + 1.0e-12) - log(minSpecValue)) / (log(maxSpecValue) - log(minSpecValue));
            dstColor = (log(dstColor + 1.0e-12) - log(minSpecValue)) / (log(maxSpecValue) - log(minSpecValue));
            c = color * 255;
            dstC = dstColor * 255;
            if(c < 0){ c = 0; } if(c > 255){c = 255;}
            if(dstC < 0){dstC= 0;} if(dstC > 255){dstC = 255;}
            image->setPixel(i, j, qRgb(0, dstC, c));
        }
    }
}

specgramViewWidget::specgramViewWidget(QWidget *parent) :
    QMyGraphWidget(parent)
{
    this->spec = NULL;
    image = NULL;
}
