#include "elescroll.h"
#include <QJsonObject>
#include <QPainter>
#include <complex>

EleScroll::EleScroll(QWidget *parent, QString dirPre, QJsonObject map) : QWidget{parent} {
    img.load(dirPre + map["id"].toString());
    QString effStr = map["effect"].toString();
    if(effStr.isNull() || effStr=="no") return;
    double effDurD = map["effectSpeed"].toInt()/2;
    if(effDurD==0) return;
    int idx = effStr.lastIndexOf(' ');
    if(idx > -1) {
        effect = effStr.at(idx+1).toLatin1();
        if(effect=='l') end = -(img.width()-1);
        else if(effect=='r') end = img.width()-1;
        else if(effect=='t') end = -(img.height()-1);
        else if(effect=='b') end = img.height()-1;
    }
    interval = ceil(effDurD/16.666666)*16.666666;
    curAdd = ceil(interval/effDurD);
}
EleScroll::EleScroll(QWidget *parent, QString imgPath, char effect, double effDur) : QWidget{parent}, effect(effect) {
    img.load(imgPath);
    if(effect==0) return;
    if(effDur==0) return;
    if(effect=='l') end = -(img.width()-1);
    else if(effect=='r') end = img.width()-1;
    else if(effect=='t') end = -(img.height()-1);
    else if(effect=='b') end = img.height()-1;
    interval = ceil(effDur/16.666666)*16.666666;
    curAdd = ceil(interval/effDur);
}

void EleScroll::paintEvent(QPaintEvent *) {
    paint(this);
}
void EleScroll::paint(QPaintDevice *that) {
    if(img.isNull()) return;
    if(timerId==0 && effect!=0 && interval!=0) {
        cur = 0;
        timerId = startTimer(interval, Qt::PreciseTimer);
    }
    QPainter painter(that);
    painter.setRenderHints(QPainter::Antialiasing|QPainter::SmoothPixmapTransform);
    if(effect=='l') {
        painter.drawPixmap(cur, 0, img);
        painter.drawPixmap(cur+img.width(), 0, img);
    } else if(effect=='r') {
        painter.drawPixmap(cur, 0, img);
        painter.drawPixmap(cur-img.width(), 0, img);
    } else if(effect=='t') {
        painter.drawPixmap(0, cur, img);
        painter.drawPixmap(0, cur+img.height(), img);
    } else if(effect=='b') {
        painter.drawPixmap(0, cur, img);
        painter.drawPixmap(0, cur-img.height(), img);
    } else painter.drawPixmap(0, 0, img);
}

void EleScroll::timerEvent(QTimerEvent *) {
    if(isVisible()) {
        if(effect=='t' || effect=='l') {
            if(cur <= end) cur = 0;
            else cur-=curAdd;
        } else if(effect=='b' || effect=='r') {
            if(cur >= end) cur = 0;
            else cur+=curAdd;
        }
        update();
        foreach(auto split, splits) split->update();
    } else if(timerId!=0) {
        killTimer(timerId);
        timerId = 0;
    }
}

void EleSplitScroll::paintEvent(QPaintEvent *) {
    scroll->paint(this);
}
