#include "DeviceCanvas.h"

DeviceCanvas::DeviceCanvas(QWidget* parent):QWidget(parent){
    m_state=0;
    mdata_width=0;
    mdata_height=0;
    mdata_pixels = 0;
    mdata_bfd=nullptr;
    m_image = nullptr;
}

DeviceCanvas::~DeviceCanvas(){
    if(nullptr!= m_image){
        delete m_image;
    }
}

void DeviceCanvas::paintEvent(QPaintEvent *event){
    if (0 == m_state) {
        return;
    }
    double cw = this->width();
    double ch = this->height();
    QRectF dst(0, 0, cw, ch);

    //
    QPainter painter;
    painter.begin(this);

    //
    if (mdata_bfd) {
        memcpy(m_image->bits(), mdata_bfd, mdata_pixels * 4);
        painter.drawImage(dst, *m_image);
    }

    //
    painter.end();
}

void DeviceCanvas::xSetGeometry(int x, int y, int width, int height){

    this->setGeometry(x, y, width, height);
}

s32 DeviceCanvas::xBeginUpdate(s32 width, s32 height){
    //
    bool b=0<width&&0<height;
    if(!b)return EError_InvalidArgs;

    //
    if(m_state)return EError_InvalidState;

    b=width==mdata_width&& height== mdata_height;
    if(b)goto error1;

    if(nullptr != m_image){
        delete m_image; m_image=nullptr;
    }
    mdata_pixels=width*height;
    mdata_width=width;
    mdata_height=height;
    m_image = new QImage(mdata_width, mdata_height, QImage::Format_RGB32);

error1:
    m_state=1;
    mdata_bfd = nullptr;
    return 0;
}
void DeviceCanvas::xEndUpdate(){
    if(0==m_state)return;

    m_state=0;
    update();
}

s32 DeviceCanvas::xUpdateData(DataFrame* dataFrame){
    if(0==m_state)return EError_InvalidState;

    mdata_bfd = (u8*)dataFrame->Bmp;

    //
    update();
    return 0;
}

s32 DeviceCanvas::xSave(const QString& fn) {
    if (0 == m_state)return EError_InvalidState;
    s32 ret;
    bool b;
    b=m_image->save(fn);
    ret = b ? 0 : EError_FileWrite;
    return ret;
}

