// SPDX-License-Identifier: GPL-2.0-only

#include "charball.h"

#include <QRandomGenerator>

CharBall::CharBall(int size, int position, QChar character)
    : currentRadius(size / 2)
    , destroyed(0)
    , color(QRandomGenerator::global()->bounded(128, 256),
          QRandomGenerator::global()->bounded(128, 256),
          QRandomGenerator::global()->bounded(128, 256))
    , currentCharacter(character)
{
    setPos(position, -2 - size);
}

QRectF CharBall::boundingRect() const
{
    return QRectF(-currentRadius, -currentRadius, (2 * currentRadius),
        (2 * currentRadius));
}

QPainterPath CharBall::shape() const
{

    QPainterPath path;
    path.addRect(
        -currentRadius, -currentRadius, 2 * currentRadius, 2 * currentRadius);
    return path;
}

void CharBall::paint(
    QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
    // Body
    painter->setBrush(color);
    painter->drawEllipse(
        -currentRadius, -currentRadius, 2 * currentRadius, 2 * currentRadius);

    if (destroyed != 0) {
        destroying();
    }
}

QChar CharBall::character() { return currentCharacter; }

void CharBall::destroy()
{
    destroyed = 56;

    update();
}

void CharBall::destroying()
{
    color = QColor(0, 0, 0);
    destroyed--;

    if (destroyed < 2) {
        destroyed = 0;
        this->setVisible(false); // delete this;
        return;
    }

    update();
}
