/***************************************************************************
 *   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/>  *
 ***************************************************************************/
/** @file
 * This file is a plugin for delete operation.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgdeleteplugin.h"

#include <QWidget>

#include <KActionCollection>
#include <KStandardAction>
#include <kaboutdata.h>
#include <KMessageBox>
#include <kpluginfactory.h>
#include <klocalizedstring.h>

#include "skgtraces.h"
#include "skgerror.h"
#include "skgobjectbase.h"
#include "skgtransactionmng.h"
#include "skgmainpanel.h"

/**
 * This plugin factory.
 */
K_PLUGIN_FACTORY(SKGDeletePluginFactory, registerPlugin<SKGDeletePlugin>();)

SKGDeletePlugin::SKGDeletePlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
    SKGInterfacePlugin(iParent), m_currentDocument(NULL)
{
    Q_UNUSED(iWidget);
    SKGTRACEINFUNC(10);
}

SKGDeletePlugin::~SKGDeletePlugin()
{
    SKGTRACEINFUNC(10);
    m_currentDocument = NULL;
}

bool SKGDeletePlugin::setupActions(SKGDocument* iDocument, const QStringList& iArgument)
{
    SKGTRACEINFUNC(10);
    Q_UNUSED(iArgument);

    m_currentDocument = iDocument;

    setComponentName("skg_delete", title());
    setXMLFile("skg_delete.rc");

    // Menu
    QStringList tmp;
    m_currentDocument->getDistinctValues("sqlite_master", "name", "type='table' AND name!='parameters'", tmp);
    QAction* actDelete = new QAction(QIcon::fromTheme("edit-delete"), i18nc("Verb, delete an item", "Delete"), this);
    connect(actDelete, &QAction::triggered, this, &SKGDeletePlugin::onDelete);
    actionCollection()->setDefaultShortcut(actDelete, Qt::Key_Delete);
    registerGlobalAction("edit_delete", actDelete, tmp, 1, -1, 200);
    return true;
}

QString SKGDeletePlugin::title() const
{
    return i18nc("Verb, delete an item", "Delete");
}

int SKGDeletePlugin::getOrder() const
{
    return 5;
}

void SKGDeletePlugin::onDelete()
{
    SKGError err;
    SKGTRACEINFUNCRC(10, err);
    if (SKGMainPanel::getMainPanel() && m_currentDocument) {
        SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
        int nb = selection.count();
        if (nb > 0) {
            if (selection[0].getRealTable() == "doctransaction") {
                err = m_currentDocument->beginTransaction("#INTERNAL#");
                IFOKDO(err, m_currentDocument->executeSqliteOrder("CREATE TRIGGER fkdc_doctransaction_doctransaction_i_parent_id "
                        "BEFORE DELETE ON doctransaction "
                        "FOR EACH ROW BEGIN "
                        "    DELETE FROM doctransaction WHERE OLD.t_name!='#INTERNAL#' AND doctransaction.id = OLD.i_parent; "
                        "END"));
                for (int i = 0; !err && i < nb; ++i) {
                    err = selection[i].remove();
                }
                m_currentDocument->executeSqliteOrder("DROP TRIGGER IF EXISTS fkdc_doctransaction_doctransaction_i_parent_id");
                SKGENDTRANSACTION(m_currentDocument,  err);
            } else {
                SKGBEGINPROGRESSTRANSACTION(*m_currentDocument, i18nc("Verb, delete an item", "Delete"), err, nb);
                for (int i = 0; !err && i < nb; ++i) {
                    err = selection[i].remove();
                    if (err && err.getReturnCode() == ERR_FORCEABLE) {
                        QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
                        int rc = KMessageBox::questionYesNo(SKGMainPanel::getMainPanel(),
                                                            err.getFullMessage() % '\n' % i18nc("Question",  "Do you want to force the deletion ?"),
                                                            i18nc("Question",  "Do you want to force the deletion ?"),
                                                            KStandardGuiItem::yes(), KStandardGuiItem::no(),
                                                            "forcedelete");
                        QApplication::restoreOverrideCursor();
                        if (rc == KMessageBox::Yes) {
                            err = selection[i].remove(true, true);
                        }
                    }
                    IFOKDO(err, m_currentDocument->stepForward(i + 1))
                }
            }
        }

        //
        KMessageBox::enableMessage("forcedelete");

        // status bar
        IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Objects deleted.")))
    }

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

#include <skgdeleteplugin.moc>
