/***************************************************************************
 *   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
 * A plugin to manage properties on objects
 *
 * @author Stephane MANKOWSKI
 */
#include "skgpropertiesplugin.h"
#include "skgpropertiesplugindockwidget.h"
#include "skgtraces.h"
#include "skgmainpanel.h"
#include "skgtransactionmng.h"

#include <QDockWidget>

#include <kactioncollection.h>
#include <kstandardaction.h>
#include <ktoolbarpopupaction.h>
#include <kaboutdata.h>

/**
 * This plugin factory.
 */
K_PLUGIN_FACTORY(SKGPropertiesPluginFactory, registerPlugin<SKGPropertiesPlugin>();)
/**
 * This plugin export.
 */
K_EXPORT_PLUGIN(SKGPropertiesPluginFactory("skg_properties", "skg_properties"))

SKGPropertiesPlugin::SKGPropertiesPlugin(QObject* iParent, const QVariantList& /*iArg*/) :
    SKGInterfacePlugin(iParent), m_dockWidget(NULL), m_dockContent(NULL)
{
    SKGTRACEIN(10, "SKGPropertiesPlugin::SKGPropertiesPlugin");
}

SKGPropertiesPlugin::~SKGPropertiesPlugin()
{
    SKGTRACEIN(10, "SKGPropertiesPlugin::~SKGPropertiesPlugin");
    m_currentDocument = NULL;
    m_dockWidget = NULL;
    m_dockContent = NULL;
    m_addPropertyMenu = NULL;
    m_addPropertyAction = NULL;
}

bool SKGPropertiesPlugin::setupActions(SKGDocument* iDocument, const QStringList& iArgument)
{
    SKGTRACEIN(10, "SKGPropertiesPlugin::setupActions");
    Q_UNUSED(iArgument);

    m_currentDocument = iDocument;

    setComponentData(KGlobal::mainComponent());
    setXMLFile("../skg_properties/skg_properties.rc");

    m_dockContent = new SKGPropertiesPluginDockWidget(m_currentDocument);
    if (m_dockContent) {
        m_dockWidget = new QDockWidget(SKGMainPanel::getMainPanel());
        if (m_dockWidget) {
            m_dockWidget->setObjectName(QString::fromUtf8("skg_properties_docwidget"));
            m_dockWidget->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
            m_dockWidget->setWindowTitle(title());
            m_dockWidget->setWidget(m_dockContent);

            // add action to control hide / display of Bookmarks
            m_dockWidget->toggleViewAction()->setShortcut(Qt::SHIFT + Qt::Key_F12);
            actionCollection()->addAction("view_properties", m_dockWidget->toggleViewAction());
        }
    }

    //Menu
    m_addPropertyAction = new KToolBarPopupAction(KIcon("feed-subscribe"), i18nc("Allows user to add a user defined property on an object", "Add property"), this);
    actionCollection()->addAction(QLatin1String("add_property"), m_addPropertyAction);
    m_addPropertyMenu = static_cast<KMenu*>(m_addPropertyAction->menu());
    connect(m_addPropertyMenu , SIGNAL(aboutToShow()), this, SLOT(onShowAddPropertyMenu()));

    m_addPropertyAction->setStickyMenu(false);
    m_addPropertyAction->setDelayed(false);

    //redoAction=KStandardAction::redo(this, SLOT(actionRedo()), actionCollection());
    if (SKGMainPanel::getMainPanel()) SKGMainPanel::getMainPanel()->registerGlobalAction("add-property", m_addPropertyAction);
    return true;
}

void SKGPropertiesPlugin::actionAddProperty()
{
    SKGTRACEIN(10, "SKGPropertiesPluginDockWidget::actionAddProperty");
    SKGError err;
    //Scope for the transaction
    QAction* act = qobject_cast<QAction*>(sender());
    if (act && m_currentDocument) {
        //Get parameters
        QStringList list = act->data().toStringList();
        QString name = list.at(0);
        QString value = list.at(1);

        //Create properties
        if (!err) {
            SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
            int nb = selection.count();
            SKGBEGINPROGRESSTRANSACTION(*m_currentDocument, i18nc("Create a user defined property", "Property creation"), err, nb);
            for (int i = 0; !err && i < nb; ++i) {
                err = selection[i].setProperty(name, value);
                if (!err)  err = m_currentDocument->stepForward(i + 1);
            }
        }
    }

    //status bar
    if (!err) {
        err = SKGError(0, i18nc("The user defined property was successfully created", "Property created"));
    }
    SKGMainPanel::displayErrorMessage(err);
}

void SKGPropertiesPlugin::onShowAddPropertyMenu()
{
    if (m_addPropertyMenu && m_currentDocument) {
        m_addPropertyMenu->clear();

        SKGObjectBase::SKGListSKGObjectBase sels = SKGMainPanel::getMainPanel()->getSelectedObjects();
        if (sels.count()) {
            QString table = sels.at(0).getRealTable();
            SKGStringListList listTmp;
            m_currentDocument->executeSelectSqliteOrder(
                "SELECT t_name, t_value FROM (SELECT t_name, t_value, COUNT(1) AS nb FROM parameters WHERE t_uuid_parent like '%-" % table % "' GROUP BY t_name, t_value) ORDER BY nb DESC LIMIT 7",
                listTmp);
            int nb = listTmp.count();
            for (int i = 1; i < nb; ++i) {
                // Should the string below be translated ??? It contains no word...
                QAction* act = m_addPropertyMenu->addAction(KIcon("feed-subscribe"), i18nc("Add a property (attribute=value)", "%1=%2", listTmp.at(i).at(0), listTmp.at(i).at(1)));
                if (act) {
                    act->setData(listTmp.at(i));
                    connect(act, SIGNAL(triggered()), this, SLOT(actionAddProperty()));
                }
            }
        }
    }
}

void SKGPropertiesPlugin::refresh()
{
    SKGTRACEIN(10, "SKGPropertiesPlugin::refresh");
    if (m_dockContent) m_dockContent->refresh();
    if (m_addPropertyAction && SKGMainPanel::getMainPanel()) m_addPropertyAction->setEnabled(SKGMainPanel::getMainPanel()->getSelectedObjects().count() > 0);
}

QDockWidget* SKGPropertiesPlugin::getDockWidget()
{
    return m_dockWidget;
}

QString SKGPropertiesPlugin::title() const
{
    return i18nc("Noun, an item's properties", "Properties");
}

int SKGPropertiesPlugin::getOrder() const
{
    return 6;
}

QStringList SKGPropertiesPlugin::tips() const
{
    QStringList output;
    output.push_back(i18nc("Description of a tip", "<p>... you can manage properties on all objects.</p>"));
    output.push_back(i18nc("Description of a tip", "<p>... you can add files or Internet links as property.</p>"));
    return output;
}

#include "skgpropertiesplugin.moc"
