#include <QResource>
#include <QPropertyAnimation>
#include <QGraphicsRectItem>
#include "hellographics.h"
#include "ui_hellographics.h"
#include "animatedpixmap.h"

HelloGraphics::HelloGraphics(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HelloGraphics)
{
    ui->setupUi(this);

    // Create a scene and paint it with gray background
    QGraphicsScene *scene = new QGraphicsScene(0, 0, 400, 300, this);
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setBackgroundBrush(QBrush(QColor(Qt::lightGray)));

    // Create a rectangle, which fills almost the entire scene
    // and set it to correct position relative to scene
    QGraphicsRectItem *rect = scene->addRect(
            0, 0, 380, 280, QPen(Qt::NoPen), QBrush(QColor(Qt::white)));
    rect->setPos(10, 10);

    // Add smaller rectangles to botton. The movable flag of the item
    // is set, so it can be dragged around with the mouse
    for (int x = 1; x < 400; x += 20) {
        QGraphicsRectItem *r = scene->addRect(
                0, 0, 18, 8, QPen(Qt::NoPen), QBrush(QColor(Qt::cyan)));
        r->setPos(x, 291);
        r->setFlags(r->flags() | QGraphicsItem::ItemIsMovable);
    }

    // Load a picture from resources and add it to center of the rectangle
    AnimatedPixmap *pixmapItem = new AnimatedPixmap(
            QPixmap::fromImage(QImage(":/pics/lemonade.jpg")), rect);
    pixmapItem->setPos(190 - pixmapItem->pixmap().width() / 2,
                       140 - pixmapItem->pixmap().height() / 2);
    pixmapItem->start();

    // Create a property animation, which scales the view
    animation = new QPropertyAnimation(this, "scale", this);
    animation->setStartValue(0.9);
    animation->setEndValue(1.1);
    animation->setDuration(10000);
    connect(animation, SIGNAL(finished()), SLOT(animationFinished()));
    animation->start();
}

void HelloGraphics::animationFinished()
{
    // Reverses the direction after every loop
    if (animation->direction() == QPropertyAnimation::Backward) {
        animation->setDirection(QPropertyAnimation::Forward);
    } else {
        animation->setDirection(QPropertyAnimation::Backward);
    }
    animation->start();
}

HelloGraphics::~HelloGraphics()
{
    delete ui;
}

void HelloGraphics::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void HelloGraphics::setScale(qreal val)
{
    QTransform transform;
    transform.scale(val, 1 / val);
    ui->graphicsView->setTransform(transform, false);
}

qreal HelloGraphics::scale() const
{
    // Getter is not needed by animation framework
    return 0;
}
