/***************************************************************************
 *   Copyright (C) 2008 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 <http://www.gnu.org/licenses/>  *
 ***************************************************************************/
#include "skgaddoperation.h"

#include <KIcon>
#include <KSaveFile>

#include <QStringBuilder>
#include <QUuid>
#include <QDir>
#include <QTextStream>
#include <KMessageBox>

SKGAddOperation::SKGAddOperation(QObject* iParent, const QVariantList& args)
    : AbstractRunner(iParent, args)
{
    setIgnoredTypes(Plasma::RunnerContext::NetworkLocation |
                    Plasma::RunnerContext::Executable |
                    Plasma::RunnerContext::ShellCommand);
    setSpeed(SlowSpeed);
    setPriority(LowPriority);
    setHasRunOptions(true);
}

void SKGAddOperation::init()
{
    reloadConfiguration();
}

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(QString("%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());

    QList<Plasma::QueryMatch> matches;
    Plasma::QueryMatch m(this);
    m.setText(i18n("Add operation %1", query));
    m.setData(query);
    m.setIcon(KIcon("skrooge"));
    m.setId(query);
    matches.append(m);

    iContext.addMatches(iContext.query(), matches);
}

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";
    KSaveFile file(fileName);
    if (file.open()) {
        QTextStream stream(&file);
        stream << "buy" << endl;
        stream << QDate::currentDate().toString("yyyy-MM-dd") << endl;
        QString s = iMatch.id().remove(0, QString("skroogeaddoperation_").length());
        int pos = s.indexOf(" ");
        if (pos == -1) {
            stream << s << endl;
            stream << "" << endl;
        } else {
            stream << s.left(pos).trimmed() << endl;
            stream << s.right(s.length() - pos - 1).trimmed() << endl;
        }

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

    // Close file
    file.finalize();
    file.close();
}

K_EXPORT_PLASMA_RUNNER(skroogeaddoperation, SKGAddOperation)

#include "skgaddoperation.moc"
