#include <QtWidgets>
#if defined(QT_PRINTSUPPORT_LIB)
#include <QtPrintSupport/qtprintsupportglobal.h>
#if QT_CONFIG(printdialog)
#include <QPrinter>
#include <QPrintDialog>
#endif
#endif

#include <iostream>
#include "scribblearea.h"
#include "colordatamodel.h"

static const qreal  MinimumDiameter = 3.0;
static const qreal  MaximumDiameter = 5.0;
static const int    RGB_255         = 255;
static const int    SIZE_INCREMENT  = 128;

//! [0]
ScribbleArea::ScribbleArea(QWidget *parent)
    : QWidget(parent)
{
    setAttribute(Qt::WA_AcceptTouchEvents);
    setAttribute(Qt::WA_StaticContents);
    modified = false;
}
//! [0]

//! [1]
bool ScribbleArea::openImage(const QString &fileName)
//! [1] //! [2]
{
    QImage loadedImage;
    if (!loadedImage.load(fileName))
        return false;

    QSize newSize = loadedImage.size().expandedTo(size());
    resizeImage(&loadedImage, newSize);
    image = loadedImage;
    modified = false;
    update();
    return true;
}
//! [2]

//! [3]
bool ScribbleArea::saveImage(const QString &fileName, const char *fileFormat)
//! [3] //! [4]
{
    bool success;

    QImage visibleImage = image;
    resizeImage(&visibleImage, size());

    if (visibleImage.save(fileName, fileFormat)) {
        modified = false;
        success = true;
    } else {
        success = false;
    }

    return success;
}

//! [4]

//! [9]
void ScribbleArea::clearImage()
//! [9] //! [10]
{
    image.fill(qRgb(RGB_255, RGB_255, RGB_255));
    modified = true;
    update();
}
//! [10]

//! [12] //! [13]
void ScribbleArea::paintEvent(QPaintEvent *event)
//! [13] //! [14]
{
    QPainter painter(this);
    const QRect rect = event->rect();
    painter.drawImage(rect.topLeft(), image, rect);
}
//! [14]

//! [15]
void ScribbleArea::resizeEvent(QResizeEvent *event)
//! [15] //! [16]
{
    if (width() > image.width() || height() > image.height()) {
        int newWidth = qMax(width() + SIZE_INCREMENT, image.width());
        int newHeight = qMax(height() + SIZE_INCREMENT, image.height());
        resizeImage(&image, QSize(newWidth, newHeight));
        update();
    }
    QWidget::resizeEvent(event);
}
//! [16]

//! [19]
void ScribbleArea::resizeImage(QImage *image, const QSize &newSize)
//! [19] //! [20]
{
    if (image->size() == newSize)
        return;

    QImage newImage(newSize, QImage::Format_RGB32);
    newImage.fill(qRgb(RGB_255, RGB_255, RGB_255));
    QPainter painter(&newImage);
    painter.drawImage(QPoint(0, 0), *image);
    *image = newImage;
}
//! [20]

//! [21]
void ScribbleArea::print()
{
#if QT_CONFIG(printdialog)
    QPrinter printer(QPrinter::HighResolution);

    QPrintDialog printDialog(&printer, this);
//! [21] //! [22]
    if (printDialog.exec() == QDialog::Accepted) {
        QPainter painter(&printer);
        QRect rect = painter.viewport();
        QSize size = image.size();
        size.scale(rect.size(), Qt::KeepAspectRatio);
        painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
        painter.setWindow(image.rect());
        painter.drawImage(0, 0, image);
    }
#endif // QT_CONFIG(printdialog)
}
//! [22]

bool ScribbleArea::event(QEvent *event)
{
    switch (event->type()) {
    case QEvent::TouchBegin:
    case QEvent::TouchUpdate:
    case QEvent::TouchEnd:
    {
        QPainter painter(&image);

        const QTouchEvent *touch = dynamic_cast<QTouchEvent *>(event);
        const QList<QTouchEvent::TouchPoint> touchPoints = dynamic_cast<QTouchEvent *>(event)->touchPoints();
        for (const QTouchEvent::TouchPoint &touchPoint : touchPoints)
        {
            switch (touchPoint.state()) {
            case Qt::TouchPointStationary:
            case Qt::TouchPointReleased:
                // don't do anything if this touch point hasn't moved or has been released
//                continue;
            case Qt::TouchPointMoved:
            case Qt::TouchPointPressed:
            default:
                {


                   QSizeF diams = touchPoint.ellipseDiameters();
                    if (diams.isEmpty()) {
                        qreal diameter = MaximumDiameter;
                        if (touch->device()->capabilities() & QTouchDevice::Pressure)
                            diameter = MinimumDiameter + (MaximumDiameter - MinimumDiameter) * touchPoint.pressure();
                        diams = QSizeF(diameter, diameter);
                    }

                    painter.setPen(Qt::NoPen);

                    QColor brushColor(ColorDataModel::getInstance().getNextColor());
                    Qt::BrushStyle brushStyle(ColorDataModel::getInstance().getPattern());
                    QBrush brush(brushColor, brushStyle);
                    painter.setBrush(brush);
//                    painter.setBrush(myPenColors.at(touchPoint.id() % myPenColors.count()));

                    painter.drawEllipse(touchPoint.pos(), diams.width() / 2, diams.height() / 2);
//                    painter.end();






                    modified = true;
                    int rad = 2;
//                    update(rect.toRect().adjusted(-rad,-rad, +rad, +rad));

                    QRectF rect(QPointF(), diams);
                    rect.moveCenter(touchPoint.pos());
                    update(rect.toRect().adjusted(-rad,-rad, +rad, +rad));
                }
                break;
            }
        }

        painter.end();

        break;
    }
    default:
        return QWidget::event(event);
    }
    return true;
}
