/***************************************************************************
 *   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 "skgpropertiesplugindockwidget.h"
#include "skgmainpanel.h"
#include "skgtraces.h"
#include "skgdocument.h"
#include "skgservices.h"
#include "skgnamedobject.h"
#include "skgobjectmodelbase.h"
#include "skgsortfilterproxymodel.h"
#include "skgtransactionmng.h"
#include "skgpropertyobject.h"

#include <kfiledialog.h>

#include <QFile>
#include <qdesktopservices.h>
#include <KMessageBox>

SKGPropertiesPluginDockWidget::SKGPropertiesPluginDockWidget(SKGDocument* iDocument)
    : SKGWidget(iDocument)
{
    SKGTRACEIN(1, "SKGPropertiesPluginDockWidget::SKGPropertiesPluginDockWidget");
    if (!iDocument) return;

    ui.setupUi(this);

    ui.kPicture->hide();

    ui.kAdd->setMaximumWidth(ui.kAdd->height());
    ui.kRemove->setMaximumWidth(ui.kRemove->height());
    ui.kSelectFile->setMaximumWidth(ui.kSelectFile->height());

    ui.kAdd->setIcon(KIcon("list-add"));
    ui.kRemove->setIcon(KIcon("list-remove"));
    ui.kSelectFile->setIcon(KIcon("document-open"));
    ui.kOpenBtn->setIcon(KIcon("skg_open"));

    ui.kForCmb->addItem(i18n("Selection"));
    ui.kForCmb->addItem(i18n("All"));

    //Add model
    SKGObjectModelBase* modelview = new SKGObjectModelBase(getDocument(), "parameters", "1=1 ORDER BY t_uuid_parent, t_name", this, "", false);
    SKGSortFilterProxyModel* modelproxy = new SKGSortFilterProxyModel(this);
    modelproxy->setSourceModel(modelview);
    ui.kView->setModel(modelproxy);

    ui.kFilterEdit->setProxy(modelproxy);

    ui.kView->setDefaultSaveParameters(getDocument(), "SKG_DEFAULT_PROPERTIES");
    connect(modelview, SIGNAL(beforeReset()), ui.kView, SLOT(saveSelection()));
    connect(modelview, SIGNAL(afterReset()), ui.kView, SLOT(resetSelection()));
    connect(ui.kView, SIGNAL(selectionChangedDelayed()), this, SLOT(onSelectionChanged()));
    connect(ui.kForCmb, SIGNAL(currentIndexChanged(int)), this, SLOT(refresh()));

    ui.kView->setTextResizable(false);
}

SKGPropertiesPluginDockWidget::~SKGPropertiesPluginDockWidget()
{
    SKGTRACEIN(1, "SKGPropertiesPluginDockWidget::~SKGPropertiesPluginDockWidget");
}

void SKGPropertiesPluginDockWidget::refresh()
{
    SKGTRACEIN(1, "SKGPropertiesPluginDockWidget::refresh");

    //Change filter
    SKGObjectModelBase* model = (SKGObjectModelBase*) ui.kView->model();
    QSortFilterProxyModel* proxyModel = qobject_cast<QSortFilterProxyModel*>(model);
    if (proxyModel) model = (SKGObjectModelBase*) proxyModel->sourceModel();

    if (model) {
        QString filter ;
        if (ui.kForCmb->currentIndex() == 1) {
            filter = "t_uuid_parent!='document'";
        } else if (ui.kForCmb->currentIndex() == 0) {
            filter = "t_uuid_parent IN (";
            SKGObjectBase::SKGListSKGObjectBase selection = SKGMainPanel::getMainPanel()->getSelectedObjects();
            int nb = selection.count();
            if (nb) {
                QString tableName;
                for (int i = 0; i < nb; ++i) {
                    if (i > 0) filter += ',';
                    else tableName = selection.at(i).getRealTable();
                    filter += '\'' % selection.at(i).getUniqueID() % '\'';
                }

                ui.kAdd->setEnabled(true);
                ui.kSelectFile->setEnabled(true);
                ui.kRemove->setEnabled(false);
                ui.kAttribute->setEnabled(true);
                ui.kValue->setEnabled(true);

                //Fill combo box
                SKGMainPanel::fillWithDistinctValue(ui.kAttribute, getDocument(), "parameters", "t_name", "t_uuid_parent like '%-" % tableName % '\'');
                SKGMainPanel::fillWithDistinctValue(ui.kValue, getDocument(), "parameters", "t_value", "t_uuid_parent like '%-" % tableName % '\'');
            } else {
                filter += "'XXX'"; //Always false
                ui.kAdd->setEnabled(false);
                ui.kSelectFile->setEnabled(false);
                ui.kRemove->setEnabled(false);
                ui.kAttribute->setEnabled(false);
                ui.kValue->setEnabled(false);
            }
            filter += ')';
        }
        filter += " ORDER BY t_uuid_parent, t_name";
        ui.kView->saveSelection();

        model->setFilter(filter);
        model->refresh();

        ui.kView->resetSelection();
    }

    ui.kView->setState("");
    if (ui.kView->isAutoResized()) ui.kView->resizeColumnsToContentsDelayed();

    onSelectionChanged();
}

void SKGPropertiesPluginDockWidget::onSelectionChanged()
{
    SKGTRACEIN(10, "SKGPropertiesPluginDockWidget::onSelectionChanged");
    int nbSelected = getNbSelectedObjects();
    ui.kPicture->hide();
    ui.kOpenBtn->hide();
    ui.kRemove->setEnabled(nbSelected > 0);
    if (nbSelected > 0) {
        SKGObjectBase::SKGListSKGObjectBase objs = getSelectedObjects();
        SKGObjectBase obj = objs.at(0);
        ui.kAttribute->setText(obj.getAttribute("t_name"));
        ui.kValue->setText(obj.getAttribute("t_value"));

        if (nbSelected == 1) {
            QStringList uuid = obj.getAttribute("t_uuid_parent").split('-');
            if (uuid.count() == 2) {
                SKGObjectBase p(getDocument(), uuid.at(1), SKGServices::stringToInt(uuid.at(0)));
                QVariant blob = p.getPropertyBlob(obj.getAttribute("t_name"));

                //Is it a copied file ?
                if (!blob.isNull()) {
                    //Yes, this is a file
                    QByteArray blob_bytes = blob.toByteArray();

                    //Save temporary file
                    QString fileName = QDir::tempPath() % '/' % obj.getAttribute("t_value");

                    QFile file(fileName);
                    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
                    if (file.open(QIODevice::WriteOnly)) {
                        file.write(blob_bytes);
                        file.flush();
                        file.close();
                        file.setPermissions(QFile::ReadOwner); //To be sure that no modifications are done

                        ui.kPicture->show();
                        ui.kOpenBtn->show();
                        ui.kPicture->showPreview(KUrl(fileName));
                    }
                }
                //Is it a linked file ?
                else if (QFile(obj.getAttribute("t_value")).exists()) {
                    ui.kPicture->show();
                    ui.kOpenBtn->show();
                    ui.kPicture->showPreview(KUrl(obj.getAttribute("t_value")));
                } else {
                    //No, Is it a http url ?
                    QUrl url(obj.getAttribute("t_value"));
                    if (!url.scheme().isEmpty()) ui.kOpenBtn->show();
                }

            }
        }
    }

    if (ui.kView->isAutoResized()) ui.kView->resizeColumnsToContentsDelayed();
}

void SKGPropertiesPluginDockWidget::onOpenFile()
{
    SKGTRACEIN(10, "SKGPropertiesPluginDockWidget::onOpenFile");
    int nbSelected = getNbSelectedObjects();
    if (nbSelected > 0) {
        SKGObjectBase::SKGListSKGObjectBase objs = getSelectedObjects();
        if (nbSelected == 1) {
            SKGObjectBase obj = objs.at(0);

            QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
            QStringList uuid = obj.getAttribute("t_uuid_parent").split('-');
            if (uuid.count() == 2) {
                SKGObjectBase p(getDocument(), uuid.at(1), SKGServices::stringToInt(uuid.at(0)));
                QVariant blob = p.getPropertyBlob(obj.getAttribute("t_name"));
                //Is it a copied file ?
                if (!blob.isNull()) {
                    //Yes, this is a file
                    //Display temporary file
                    QString fileName = QDir::tempPath() % '/' % obj.getAttribute("t_value");
                    if (!QDesktopServices::openUrl(KUrl(fileName))) {
                        QString fileNameToSave = SKGMainPanel::getSaveFileName("kfiledialog:///IMPEXP", "" , SKGMainPanel::getMainPanel());
                        if (!fileNameToSave.isEmpty()) {
                            QFile(fileName).copy(fileNameToSave);
                        }
                    }
                }
                //Is it a linked file?
                else if (QFile().exists(obj.getAttribute("t_value"))) {
                    QDesktopServices::openUrl(KUrl(obj.getAttribute("t_value")));
                } else {
                    //No, Is it a http url ?
                    QUrl url(obj.getAttribute("t_value"));
                    if (!url.scheme().isEmpty()) QDesktopServices::openUrl(url);
                }
            }
            QApplication::restoreOverrideCursor();
        }
    }

    if (ui.kView->isAutoResized()) ui.kView->resizeColumnsToContentsDelayed();
}

void SKGPropertiesPluginDockWidget::onAddProperty()
{
    SKGTRACEIN(10, "SKGPropertiesPluginDockWidget::onAddProperty");
    SKGError err;
    QStringList listUUID;
    //Scope for the transaction
    {
        //Get parameters
        QString name = ui.kAttribute->text();
        QString value = ui.kValue->text();
        QVariant blob;
        QFile file(value);
        if (file.exists()) {
            int mode = KMessageBox::questionYesNoCancel(this, i18nc("Question", "Do you want copy or link the file?"),
                       QString(),
                       KGuiItem(i18nc("Question", "Copy") , "edit-copy"),
                       KGuiItem(i18nc("Question", "Link") , "edit-link"));

            if (mode == KMessageBox::Cancel) return;
            if (mode == KMessageBox::Yes) {
                //Value is a file name ==> blob
                if (!file.open(QIODevice::ReadOnly)) {
                    err = SKGError(ERR_INVALIDARG, i18nc("Error message: could not open the requested file", "Open file '%1' failed", value));
                } else {
                    QByteArray blob_bytes = file.readAll();
                    if (!blob_bytes.count()) {
                        err = SKGError(ERR_INVALIDARG, i18nc("Error message: could not open the requested file", "Open file '%1' failed", value));
                    } else {
                        blob = blob_bytes;
                        value = QFileInfo(value).fileName();
                    }

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

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

                if (!err) {
                    listUUID.push_back(prop.getUniqueID());
                    err = getDocument()->stepForward(i + 1);
                }
            }
        }
    }

    //status bar
    if (!err) {
        err = SKGError(0, i18nc("The user defined property was successfully created", "Property created"));
        ui.kView->selectObjects(listUUID, true);
    }
    SKGMainPanel::displayErrorMessage(err);
}

void SKGPropertiesPluginDockWidget::onSelectFile()
{
    QString fileName = KFileDialog::getOpenFileName(KUrl("kfiledialog:///IMPEXP"), "" , this);
    ui.kValue->setText(fileName);
}

void SKGPropertiesPluginDockWidget::onRemoveProperty()
{
    SKGError err;
    SKGTRACEINRC(10, "SKGPropertiesPluginDockWidget::onRemoveProperty", err);
    {
        SKGObjectBase::SKGListSKGObjectBase selection = getSelectedObjects();
        int nb = selection.count();
        SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Verb, delete an item", "Delete"), err, nb);
        for (int i = 0; !err && i < nb; ++i) {
            err = selection[i].remove();
            if (!err) err = getDocument()->stepForward(i + 1);
        }
    }

    //status bar
    if (!err) err = SKGError(0, i18nc("The user defined property was successfully deleted", "Properties deleted."));
    else err.addError(ERR_FAIL, i18nc("Error message: Could not delete an item", "Delete failed"));

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

void SKGPropertiesPluginDockWidget::cleanEditor()
{
    if (getNbSelectedObjects() == 0) {
        ui.kAttribute->setText("");
        ui.kValue->setText("");
    }
}

QWidget* SKGPropertiesPluginDockWidget::mainWidget() const
{
    return ui.kView;
}

#include "skgpropertiesplugindockwidget.moc"


