/***************************************************************************
 *   Copyright (C) 2020 by S. MANKOWSKI / G. DE BURE support@mankowski.fr  *
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) 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 <https://www.gnu.org/licenses/>  *
 ***************************************************************************/
#include "skgaddoperation.h"

#include <qdir.h>
#include <qicon.h>
#include <qsavefile.h>
#include <qstringbuilder.h>
#include <qtextstream.h>
#include <quuid.h>

#include <klocalizedstring.h>
#include <kmessagebox.h>

#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
#define SKGENDL endl
#else
#define SKGENDL Qt::endl
#endif

SKGAddOperation::SKGAddOperation(QObject* iParent, const QVariantList& args)
    : AbstractRunner(iParent, args)
{
    setIgnoredTypes(Plasma::RunnerContext::NetworkLocation |
                    Plasma::RunnerContext::FileSystem);
    setPriority(HighPriority);
}

void SKGAddOperation::reloadConfiguration()
{
    KConfigGroup c = config();
    m_triggerWord = c.readEntry("buy", i18nc("default keyword for krunner plugin", "buy"));
    if (!m_triggerWord.isEmpty()) {
        m_triggerWord.append(' ');
    }

    QList<Plasma::RunnerSyntax> listofSyntaxes;
    Plasma::RunnerSyntax syntax(QStringLiteral("%1:q:").arg(m_triggerWord), i18n("Add a new operation in skrooge"));
    syntax.setSearchTermDescription(i18n("amount payee"));
    syntax.addExampleQuery(i18nc("Example of krunner command", "%1 10 computer", m_triggerWord));
    listofSyntaxes.append(syntax);
    setSyntaxes(listofSyntaxes);
}

void SKGAddOperation::match(Plasma::RunnerContext& iContext)
{
    QString query = iContext.query();
    if (!query.startsWith(m_triggerWord)) {
        return;
    }
    query = query.remove(0, m_triggerWord.length());

    Plasma::QueryMatch m(this);
    m.setText(i18n("Add operation %1", query));
    m.setData(query);
    m.setIcon(QIcon::fromTheme(QStringLiteral("skrooge")));
    m.setId(query);

    iContext.addMatch(m);
}

void SKGAddOperation::run(const Plasma::RunnerContext& iContext, const Plasma::QueryMatch& iMatch)
{
    Q_UNUSED(iContext)

    QString dirName = QDir::homePath() % "/.skrooge/";
    QDir().mkpath(dirName);
    QString fileName = dirName % "add_operation_" % QUuid::createUuid().toString() % ".txt";
    QSaveFile file(fileName);
    if (file.open(QIODevice::WriteOnly)) {
        QTextStream stream(&file);
        stream << "buy" << SKGENDL;
        stream << QDate::currentDate().toString(QStringLiteral("yyyy-MM-dd")) << SKGENDL;
        QString s = iMatch.id().remove(0, QStringLiteral("skroogeaddoperation_").length());
        int pos = s.indexOf(QStringLiteral(" "));
        if (pos == -1) {
            stream << s << SKGENDL;
            stream << "" << SKGENDL;
        } else {
            stream << s.left(pos).trimmed() << SKGENDL;
            stream << s.right(s.length() - pos - 1).trimmed() << SKGENDL;
        }

        // Close file
        file.commit();

        KMessageBox::information(nullptr, i18nc("Information message", "Operation created"));
    } else {
        KMessageBox::error(nullptr, i18nc("Error message: Could not create a file", "Creation of file %1 failed", fileName));
    }
}

K_EXPORT_PLASMA_RUNNER(skroogeaddoperation, SKGAddOperation)
#include "skgaddoperation.moc"
