/*
 * Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
 *
 * Author:     kirigaya <kirigaya@mkacg.com>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "borderwidget.h"
#include "ddlog.h"

BorderWidget::BorderWidget(QWidget *parent)
    : DFrame(parent)
    , m_checked(false)
{
    qCDebug(app) << "BorderWidget constructor started";

    setLineWidth(0);
    qCDebug(app) << "BorderWidget initialization completed";
}

void BorderWidget::setPixmap(const QPixmap &pixmap)
{
    qCDebug(app) << "Setting pixmap, size:" << pixmap.size();

    m_pixmap = pixmap;
    m_size = QSize(420, 264) * devicePixelRatioF();

    update();
}

void BorderWidget::setChecked(bool checked)
{
    qCDebug(app) << "Border checked state changed to:" << checked;

    m_checked = checked;

    update();
}

void BorderWidget::updateInterface(float f)
{
    qCDebug(app) << "Updating interface with scale factor:" << f;

    m_size = m_pixmap.size() * static_cast<qreal>(f);
    update();
}

void BorderWidget::paintEvent(QPaintEvent *event)
{
    DFrame::paintEvent(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    QRect pixRect(QPoint(0, 0), (m_size + QSize(7, 7)) / devicePixelRatioF());
    pixRect.moveCenter(rect().center());

    // draw background
    QPainterPath contentPath;
    contentPath.addRoundedRect(pixRect, 8, 8);
    painter.setClipPath(contentPath);
    QPixmap pix = m_pixmap.scaled(pixRect.size() * devicePixelRatioF(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    painter.drawPixmap(pixRect, pix);

    if (!m_checked) {
        QPen pen(QColor(0, 0, 0, int(0 * 255)));
        pen.setWidth(1);
        painter.setPen(pen);
        QPainterPath Frame;
        QRect frameRect = pixRect;
        frameRect.setHeight(frameRect.height() + 6);
        frameRect.moveCenter(rect().center());
        Frame.addRoundedRect(frameRect, 8, 8);
        painter.setClipPath(Frame);
        painter.drawPath(Frame);
    }

    // draw border
    QPainterPath path;
    path.addRoundedRect(rect().adjusted(3, 3, -3, -3), 8, 8);
    painter.setClipRect(QRect(), Qt::NoClip);
    if (m_checked) {
        QColor color = DGuiApplicationHelper::instance()->applicationPalette()
                .highlight().color();
        QPen pen(color);
        pen.setWidth(4);

        painter.setPen(pen);
        painter.drawPath(path);
    }
}
