/*
    SPDX-FileCopyrightText: 2007-2008 Robert Knight <robertknight@gmail.com>
    SPDX-FileCopyrightText: 2020 Tomaz Canabrava <tcanabrava@gmail.com>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "EscapeSequenceUrlFilterHotSpot.h"

#include <KIO/JobUiDelegateFactory>
#include <KIO/OpenUrlJob>

#include <QApplication>
#include <QDebug>
#include <QDrag>
#include <QMimeData>
#include <QMouseEvent>

#include "terminalDisplay/TerminalDisplay.h"

using namespace Konsole;

EscapeSequenceUrlHotSpot::EscapeSequenceUrlHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QString &text, const QString &url)
    : HotSpot(startLine, startColumn, endLine, endColumn)
    , _text(text)
    , _url(url)
{
    setType(EscapedUrl);
}

void EscapeSequenceUrlHotSpot::activate(QObject *obj)
{
    Q_UNUSED(obj)

    auto *job = new KIO::OpenUrlJob(QUrl(_url));
    job->setUiDelegate(KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, QApplication::activeWindow()));
    job->start();
}

bool EscapeSequenceUrlHotSpot::hasDragOperation() const
{
    return true;
}

void EscapeSequenceUrlHotSpot::startDrag()
{
    auto *drag = new QDrag(this);
    auto *mimeData = new QMimeData();
    mimeData->setText(_url);
    mimeData->setUrls({QUrl(_url)});

    drag->setMimeData(mimeData);
    // TODO add drag pixmap containing the URL.
    drag->exec(Qt::CopyAction);
}

void EscapeSequenceUrlHotSpot::mouseEnterEvent(TerminalDisplay *td, QMouseEvent *ev)
{
    HotSpot::mouseEnterEvent(td, ev);

    td->setHoverLinkIndicator(this->_url);
}

void EscapeSequenceUrlHotSpot::mouseLeaveEvent(TerminalDisplay *td, QMouseEvent *ev)
{
    HotSpot::mouseLeaveEvent(td, ev);

    td->setHoverLinkIndicator(QStringLiteral(""));
}
