#include "aditem.h"
#include <QPainter>
#include <QDebug>


ADItem::ADItem(int id, adType type, QList<QImage *> *images_, QRectF geometry, QGraphicsItem *parent) :
    QGraphicsItem(parent)
{
    m_id = id;
    m_type = type;
    anim = 0;
    images = images_;
    animcount = images->size();
    QSize size = images->at(0)->size();
    staticImage = false;
    if (animcount == 1) staticImage = true;
    if (geometry.isNull()) br = QRect(QPoint(-(size.width()/2), -(size.height()/2)), size);
    else br = geometry;
    hasBar = false;
    switch (type)
    {
    case Alien :
        setFlag(QGraphicsItem::ItemIsSelectable);
        barValue = 1.f;
        hasBar = true;
        setZValue(-1.f);
    break;
    case Other :
    default:
        setZValue(3.f);
    }
    if (staticImage)
    {
        setCacheMode(QGraphicsItem::ItemCoordinateCache);
        img = (*images)[0];
    }
    cmode = QPainter::CompositionMode_SourceOver;
}


ADItem::ADItem(QPoint id, QImage *image, QRectF geometry, QGraphicsItem *parent) :
    QGraphicsItem(parent)
{
    hasBar = true;
    barValue = 0.f;
    m_type = Tower;
    setZValue(-2.f);
    m_tid = id;
    img = image;
    QSize size = img->size();
    if (geometry.isNull()) br = QRectF(QPoint(-(size.width()/2),-(size.height()/2)),size);
    else br = geometry;
    staticImage = true;
    setFlag(QGraphicsItem::ItemIsSelectable);
    cmode = QPainter::CompositionMode_SourceOver;
}


void ADItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
    painter->setCompositionMode(cmode);
    if (staticImage)
        painter->drawImage(br,*img);
    else painter->drawImage(br, *(images->at(qRound(anim))));
    //	if (isSelected())
    //	{
    //		painter->setPen(Qt::red);
    //		painter->drawRect(br);
    //	}
}


QRectF ADItem::boundingRect() const
{
    return br;
}

void ADItem::next(float step)
{
    if (staticImage) return;
    anim+=step;
    if (qRound(anim) >= animcount)
        anim = 0;
}

