#include "elevideo.h"
#include "tools.h"
#include <QGraphicsVideoItem>
#include <QMediaPlaylist>
#include <QMessageBox>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>

EleVideo::EleVideo(QString path, int w, int h, QWidget *parent) : QGraphicsView{parent} {
    setFrameStyle(QFrame::NoFrame);
    setScene(new QGraphicsScene(this));
    setBackgroundBrush(QColor(0,0,0));
    auto videoItem = new QGraphicsVideoItem();
    videoItem->setSize(QSize(w,h));
    videoItem->setAspectRatioMode(Qt::IgnoreAspectRatio);
    scene()->addItem(videoItem);
    player = new QMediaPlayer(videoItem);
    player->setVideoOutput(videoItem);
    connect(player, &QMediaPlayer::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status){
        if(status==QMediaPlayer::EndOfMedia) {
            if(player->state() != QMediaPlayer::PlayingState && isVisible()) player->play();
        }
    });
    void(QMediaPlayer::*player_error)(QMediaPlayer::Error) = &QMediaPlayer::error;
    connect(player, player_error, this, [this](QMediaPlayer::Error error){
        QMessageBox::critical(this, "Video Error", Tools::playerErrStr(error)+": "+player->errorString());
    });
    player->setMedia(QUrl::fromLocalFile(path));
}

void EleVideo::showEvent(QShowEvent *) {
    if(player!=nullptr && player->state() != QMediaPlayer::PlayingState) player->play();
}
void EleVideo::hideEvent(QHideEvent *) {
    if(player!=nullptr) player->stop();
}
