/*
    SPDX-FileCopyrightText: 2014-2023 Anne Jan Brouwer <brouwer@annejan.com>
    SPDX-FileCopyrightText: 2018 Claudio Maradonna <penguyman@stronzi.org>
    SPDX-FileCopyrightText: 2023 g10 Code GmbH
    SPDX-FileContributor: Sune Stolborg Vuorela <sune@vuorela.dk>

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

#include "clipboardhelper.h"
#include "config.h"

#include <KLocalizedString>

#include <QApplication>
#include <QClipboard>
#include <QDialog>
#include <QLabel>
#include <QMainWindow>
#include <QPixmap>
#include <QStatusBar>
#include <QVBoxLayout>

ClipboardHelper::ClipboardHelper(QMainWindow *mainWindow)
    : QObject(mainWindow)
    , m_mainWindow(mainWindow)
    , clippedText(QString())
{
    setClipboardTimer();
    clearClipboardTimer.setSingleShot(true);
    connect(&clearClipboardTimer, &QTimer::timeout, this, &ClipboardHelper::clearClipboard);
}

ClipboardHelper::~ClipboardHelper() = default;

void ClipboardHelper::setClippedText(const QString &password)
{
    clippedText = password;
}
void ClipboardHelper::clearClippedText()
{
    clippedText = QString{};
}

void ClipboardHelper::setClipboardTimer()
{
    clearClipboardTimer.setInterval(1000 * Config::self()->clipboardAutoClearTime());
}

/**
 * Clears the clipboard if we filled it
 */
void ClipboardHelper::clearClipboard()
{
    QClipboard *clipboard = QApplication::clipboard();
    bool cleared = false;
    if (this->clippedText == clipboard->text(QClipboard::Selection)) {
        clipboard->clear(QClipboard::Selection);
        clipboard->setText(QString{}, QClipboard::Selection);
        cleared = true;
    }
    if (this->clippedText == clipboard->text(QClipboard::Clipboard)) {
        clipboard->clear(QClipboard::Clipboard);
        cleared = true;
    }
    if (cleared) {
        Q_EMIT showMessage(i18n("Clipboard cleared"), 2000);
    } else {
        Q_EMIT showMessage(i18n("Clipboard not cleared"), 2000);
    }

    clippedText.clear();
}

/**
 * @brief MainWindow::copyTextToClipboard copies text to your clipboard
 * @param text
 */
void ClipboardHelper::copyTextToClipboard(const QString &text)
{
    QClipboard *clip = QApplication::clipboard();
    clip->setText(text, QClipboard::Clipboard);

    clippedText = text;
    Q_EMIT showMessage(i18n("Copied to clipboard"), 2000);
    if (Config::self()->clipboardAutoClearEnabled()) {
        clearClipboardTimer.start();
    }
}
