/***************************************************************************
 *   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
 * filetered SKGTableView.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgfilteredtableview.h"

#include <QDomDocument>
#include <KLineEdit>

#include "skgsortfilterproxymodel.h"
#include "skgmainpanel.h"

SKGFilteredTableView::SKGFilteredTableView(QWidget* iParent)
    : QWidget(iParent), m_objectModel(NULL), m_refreshNeeded(true)
{
    ui.setupUi(this);
    ui.kTitle->hide();
    ui.kResetInternalFilter->hide();
    connect(ui.kResetInternalFilter, SIGNAL(clicked()), this, SLOT(resetFilter()));
    ui.kResetInternalFilter->setIcon(KIcon("dialog-cancel"));
    ui.kConfigure->setIcon(KIcon("configure"));
    ui.kConfigure->setPopupMode(QToolButton::InstantPopup);
    ui.kConfigure->setAutoRaise(true);
    ui.kConfigure->setMenu(ui.kView->getHeaderMenu());

    connect(ui.kShow, SIGNAL(stateChanged()), this, SLOT(onFilterChanged()), Qt::QueuedConnection);
    if (SKGMainPanel::getMainPanel()) {
        connect(SKGMainPanel::getMainPanel(), SIGNAL(currentPageChanged()), this, SLOT(pageChanged()), Qt::QueuedConnection);
    }
}

SKGFilteredTableView::~SKGFilteredTableView()
{
    m_objectModel = NULL;
}

QString SKGFilteredTableView::getState()
{
    QDomDocument doc("SKGML");
    QDomElement root = doc.createElement("parameters");
    doc.appendChild(root);

    root.setAttribute("show", ui.kShow->getState());
    root.setAttribute("filter", getSearchField()->lineEdit()->text());

    // Memorize table settings
    root.setAttribute("view", ui.kView->getState());
    return doc.toString();
}

void SKGFilteredTableView::setState(const QString& iState)
{
    QDomDocument doc("SKGML");
    doc.setContent(iState);
    QDomElement root = doc.documentElement();

    QString show2 = root.attribute("show");
    QString filter = root.attribute("filter");

    if (!show2.isEmpty()) {
        ui.kShow->setState(show2);
    }
    getSearchField()->setText(filter);

    if (m_objectModel) {
        bool previous = m_objectModel->blockRefresh(true);
        onFilterChanged();
        m_objectModel->blockRefresh(previous);
    }

    // !!! Must be done here after onFilterChanged
    ui.kView->setState(root.attribute("view"));
}

SKGShow* SKGFilteredTableView::getShowWidget() const
{
    return ui.kShow;
}

SKGTreeView* SKGFilteredTableView::getView() const
{
    return ui.kView;
}

KFilterProxySearchLine* SKGFilteredTableView::getSearchField() const
{
    return ui.kFilterEdit;
}

void SKGFilteredTableView::onFilterChanged()
{
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    // Update model
    if (m_objectModel && ui.kShow->isEnabled() && m_objectModel->setFilter(ui.kShow->getWhereClause())) {
        m_objectModel->dataModified();
    }

    QApplication::restoreOverrideCursor();
}

void SKGFilteredTableView::pageChanged()
{
    if (m_refreshNeeded) {
        dataModified("", 0);
    }
}

void SKGFilteredTableView::dataModified(const QString& iTableName, int iIdTransaction)
{
    Q_UNUSED(iIdTransaction);

    if ((m_objectModel && iTableName == m_objectModel->getTable()) || iTableName.isEmpty()) {
        SKGTabPage* page = SKGTabPage::parentTabPage(this);
        if (page != NULL && page != SKGMainPanel::getMainPanel()->currentPage()) {
            m_refreshNeeded = true;
            return;
        }
        m_refreshNeeded = false;

        if (getView()->isAutoResized()) {
            getView()->resizeColumnsToContentsDelayed();
        }

        getView()->onSelectionChanged();
    }
}
void SKGFilteredTableView::setModel(SKGObjectModelBase* iModel)
{
    m_objectModel = iModel;
    if (m_objectModel) {
        SKGSortFilterProxyModel* modelProxy = new SKGSortFilterProxyModel(this);
        modelProxy->setSourceModel(m_objectModel);
        modelProxy->setSortRole(Qt::UserRole);
        modelProxy->setDynamicSortFilter(true);

        getSearchField()->setProxy(modelProxy);

        ui.kView->setModel(modelProxy);

        ui.kView->sortByColumn(0, Qt::AscendingOrder);

        connect(m_objectModel, SIGNAL(beforeReset()), ui.kView, SLOT(saveSelection()));
        connect(m_objectModel, SIGNAL(afterReset()), ui.kView, SLOT(resetSelection()));
        connect(m_objectModel->getDocument(), SIGNAL(tableModified(QString,int,bool)), this, SLOT(dataModified(QString,int)), Qt::QueuedConnection);
    }
    dataModified("", 0);
}

void SKGFilteredTableView::resetFilter()
{
    getShowWidget()->setEnabled(true);
    ui.kTitle->hide();
    ui.kResetInternalFilter->hide();

    m_objectModel->setFilter("");
    m_objectModel->refresh();
}

void SKGFilteredTableView::setFilter(const KIcon& iIcon, const QString& iText, const QString& iWhereClause)
{
    if (m_objectModel && !iWhereClause.isEmpty()) {
        getShowWidget()->setEnabled(false);

        QFontMetrics fm(fontMetrics());
        ui.kTitle->setComment("<html><body><b>" % SKGServices::stringToHtml(fm.elidedText(iText, Qt::ElideMiddle, 2000)) % "</b></body></html>");
        ui.kTitle->setToolTip(iText);
        ui.kResetInternalFilter->show();

        ui.kTitle->setPixmap(KIcon(iIcon).pixmap(22, 22), KTitleWidget::ImageLeft);

        m_objectModel->setFilter(iWhereClause);
        m_objectModel->refresh();
    }
}

#include "skgfilteredtableview.moc"

