#include "elegif.h"
#include <QPainter>
#include <QMovie>

EleGif::EleGif(QString path, QWidget *parent) : QWidget{parent} {
    movie = new QMovie(path, QByteArray(), this);
    movie->setCacheMode(QMovie::CacheAll);
    movie->jumpToFrame(0);
}

void EleGif::paintEvent(QPaintEvent *){
    QPainter painter(this);
    if(movie!=nullptr) {
        painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
        painter.drawPixmap(0, 0, width(), height(), movie->currentPixmap());
        if(timer==nullptr) {
            timer = new SyncTimer(movie->nextFrameDelay());
            connect(timer, &SyncTimer::timeout, this, &EleGif::sltNext, Qt::BlockingQueuedConnection);
            timer->start();
        }
    }
}
void EleGif::sltNext(){
    if(isVisible()) {
        movie->jumpToNextFrame();
        timer->inter = movie->nextFrameDelay();
        update();
    } else if(timer!=nullptr) {
        timer->stop();
        timer = nullptr;
    }
}
