#include "elevideo.h"
#include "tools.h"
#include <QPainter>
#include <QMessageBox>
#include <QMutex>

static void *lock(void *opaque, void **planes) {
    auto that = (EleVideo *) opaque;
    that->imgRaw = QImage(that->mWidth, that->mHeight, QImage::Format_RGB32);
    *planes = that->imgRaw.bits();  /*tell VLC to put decoded data to this buffer*/
    return 0; /* picture identifier, not needed here */
}
static void unlock(void *opaque, void *picture, void *const *planes) {
}

static void display(void *opaque, void *picture) {
    auto that = (EleVideo *) opaque;
    that->emDisplay(that->imgRaw);
}

EleVideo::EleVideo(QString path, QWidget *parent) : QWidget{parent} {
    vlc = libvlc_new(0, NULL);
    auto pathChars = path.replace("/","\\").toUtf8();
    auto media = libvlc_media_new_path(vlc, pathChars.data());
    qDebug()<<"media"<<media;
    libvlc_media_parse(media);
    //libvlc_media_add_option(media, ":avcodec-hw=none");
    player = libvlc_media_player_new_from_media(media);
    libvlc_media_release(media);
    libvlc_video_get_size(player, 0, &mWidth, &mHeight);
    qDebug()<<"  size"<<mWidth<<mHeight;
    libvlc_video_set_callbacks(player, lock, unlock, display, this);
    libvlc_video_set_format(player, "RV32", mWidth, mHeight, mWidth * 4);
    libvlc_video_set_adjust_int(player, libvlc_adjust_Enable, 1);
    libvlc_video_set_adjust_float(player, libvlc_adjust_Brightness, 1.1); //Value ranges from 0.0 to 2.0
    libvlc_video_set_adjust_float(player, libvlc_adjust_Contrast, 1.5);
    libvlc_video_set_adjust_float(player, libvlc_adjust_Saturation, 3);
    connect(this, &EleVideo::emDisplay, this, [this](QImage aimg){
        img = aimg;
        update();
    });
}

//void EleVideo::mouseDoubleClickEvent(QMouseEvent *) {
//    qDebug()<<"img"<<img;
//    qDebug()<<"img"<<player->img;
//    qDebug()<<"viCurTime"<<player->viCurTime;
//    qDebug()<<"viSize"<<player->viSize;
//}
void EleVideo::showEvent(QShowEvent *) {
    if(player!=nullptr) libvlc_media_player_play(player);
}
void EleVideo::hideEvent(QHideEvent *) {
    if(player!=nullptr) libvlc_media_player_stop(player);
}

void EleVideo::paintEvent(QPaintEvent *e) {
    QWidget::paintEvent(e);
    QPainter painter(this);
    painter.drawImage(QRectF(0, 0, width(), height()), img);
}
