#include "customitem.h"
#include <QTimer>
#include <QPainter>

CustomItem::CustomItem(QQuickItem *parent) : QQuickPaintedItem(parent)
{
    connect(this, &QQuickItem::widthChanged, this, &CustomItem::onSizeChanged);
    connect(this, SIGNAL(heightChanged()), SLOT(onSizeChanged()));

    // 左ボタンの入力を受け付け、mousePressイベントを発生させる
    setAcceptedMouseButtons(Qt::LeftButton);

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(15);
}

void CustomItem::mousePressEvent(QMouseEvent *ev)
{
    Q_UNUSED(ev);
    color = Qt::GlobalColor::red;
    // rgb形式の例
    //color = QColor(255, 0, 0);
}

void CustomItem::paint(QPainter *p)
{
    frame += 2;
    qreal w = width(), h = height();

    qreal r = qMin(w - 1, h - 1) / 2.0;
    qreal s = r / 20.0;
    const qreal ps = 1.0;
    qreal sz = r - 2 * ps - s;

    // アンチエイリアスを有効にして描画
    p->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    // colorの色を持つペンを作成
    QPen pen(color);
    pen.setWidthF(ps);
    p->setPen(pen);

    QPointF cp = QPointF(w / 2, h / 2);

    const int all = 120;
    const qreal start = 30, end = 90;
    QRectF drc;
    for(int i = 0; i < 4; i++){
        qreal pos = (frame - i * 30) % all;
        qreal opq = (pos - end) / (start - end);
        if(opq < 0 || opq > 1) opq = 0;
        switch(i){
        case 3: drc = QRectF(cp.x() - s - sz, cp.y() + s, sz, sz); break;
        case 2: drc = QRectF(cp.x() + s, cp.y() + s, sz, sz); break;
        case 1: drc = QRectF(cp.x() + s, cp.y() - s - sz, sz, sz); break;
        case 0: drc = QRectF(cp.x() -s - sz, cp.y() - s - sz, sz, sz); break;
        }

        color.setAlpha(static_cast<int>(opq * 255.0));
        p->setBrush(QBrush(color));

        p->drawRect(drc);
    }

    color.setAlpha(255);
}

void CustomItem::onSizeChanged()
{
    setX((parentItem()->width() - width()) / 2.0);
    setY((parentItem()->height() - height()) / 2.0);
}
