#include "DropFileWidget.h"

// Qt
#include <QDebug>
#include <QDropEvent>
#include <QFileDialog>
#include <QIcon>
#include <QLabel>
#include <QMimeData>
#include <QStandardPaths>
#include <QVBoxLayout>

DropFileWidget::DropFileWidget(QWidget *parent)
    : QWidget(parent)
{
    setAcceptDrops(true);

    QVBoxLayout *layout = new QVBoxLayout(this);
    setLayout(layout);

    QIcon icon(":/deps/dropFiles.png");
    QLabel *iconLabel = new QLabel(this);
    iconLabel->setPixmap(icon.pixmap(300, 300));
    iconLabel->setAlignment(Qt::AlignCenter);
    layout->addWidget(iconLabel);
}

void DropFileWidget::dragEnterEvent(QDragEnterEvent *e)
{
    if (e->mimeData()->hasUrls())
        e->acceptProposedAction();
    else
        e->ignore();
}

void DropFileWidget::dragMoveEvent(QDragMoveEvent *e)
{
    if (e->mimeData()->hasUrls())
        e->acceptProposedAction();
    else
        e->ignore();
}

void DropFileWidget::dropEvent(QDropEvent *e)
{
    if (e->mimeData()->hasUrls())
    {
        QStringList paths;
        const auto urls = e->mimeData()->urls();
        for (const QUrl &url : urls)
        {
            if (url.isLocalFile())
            {
                const QString path = url.toLocalFile();
                if (!path.isEmpty())
                    paths << path;
            }
        }

        if (!paths.isEmpty())
        {
            emit filesDropped(paths);
            e->acceptProposedAction();
        }
        else
            e->ignore();
    }
}

void DropFileWidget::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton)
        selectFiles();
    QWidget::mousePressEvent(e);
}

void DropFileWidget::selectFiles()
{
    auto files = QFileDialog::getOpenFileNames(
        this
        , tr("Select config file")
        , QStandardPaths::writableLocation(QStandardPaths::HomeLocation)
    );
    emit filesDropped(files);
}
