/***************************************************************************
 *   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 class managing widget.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgtabpage.h"
#include "skgnodeobject.h"
#include "skgservices.h"
#include "skgdocument.h"
#include "skgtransactionmng.h"
#include "skgtraces.h"
#include "skgmainpanel.h"
#include "skgtreeview.h"

#include "kmessagebox.h"

#include <QtGui/QWidget>
#include <QWebView>

#include <qmath.h>
#include "math.h"

SKGTabPage::SKGTabPage(SKGDocument* iDocument)
    : SKGWidget(iDocument)
{
    SKGTRACEIN(5, "SKGTabPage::SKGTabPage");

    //Save original size
    m_fontOriginalPointSize = this->font().pointSize(); //Use this instead of zoomableWidget()
}

SKGTabPage::~SKGTabPage()
{
    SKGTRACEIN(5, "SKGTabPage::~SKGTabPage");
}

bool SKGTabPage::close()
{
    SKGTRACEIN(5, "SKGTabPage::close");
    overwrite();
    return QWidget::close();
}

void SKGTabPage::setBookmarkID(const QString& iId)
{
    m_bookmarkID = iId;
}

QString SKGTabPage::getBookmarkID()
{
    return m_bookmarkID;
}
QList<SKGTabPage::SKGPageHistoryItem> SKGTabPage::getPreviousPages()
{
    return m_previousPages;
}

void SKGTabPage::setPreviousPages(const QList<SKGTabPage::SKGPageHistoryItem>& iPages)
{
    m_previousPages = iPages;
}

QList<SKGTabPage::SKGPageHistoryItem> SKGTabPage::getNextPages()
{
    return m_nextPages;
}

void SKGTabPage::setNextPages(const QList<SKGTabPage::SKGPageHistoryItem>& iPages)
{
    m_nextPages = iPages;
}

bool SKGTabPage::isOverwriteNeeded()
{
    //Is this widget linked to a bookmark ?
    if (!m_bookmarkID.isEmpty()) {
        //Yes. Is state modified ?
        SKGNodeObject node(getDocument(), SKGServices::stringToInt(m_bookmarkID));
        if (node.exist()) {
            QStringList data = SKGServices::splitCSVLine(node.getData());
            QString fullname = node.getFullName();
            if (data.count() > 2) {
                QString currentState = getState().trimmed();
                QString oldState = data[2].trimmed();
                currentState.remove('\n');
                oldState.remove('\n');
                SKGTRACEL(20) << "oldState      =[" << oldState << ']' << endl;
                SKGTRACEL(20) << "currentState  =[" << currentState << ']' << endl;
                SKGTRACEL(20) << "Bookmark diff =" << (currentState != oldState ? "TRUE" : "FALSE") << endl;
                return (currentState != oldState);
            }
        }
    } else {
        //No. It is a page opened from context or from another page
        QString name = getDefaultStateAttribute();
        if (!name.isEmpty()) {
            QString currentState = getState().trimmed();
            QString oldState = getDocument()->getParameter(name);
            currentState.remove('\n');
            oldState.remove('\n');
            SKGTRACEL(20) << "oldState      =[" << oldState << ']' << endl;
            SKGTRACEL(20) << "currentState  =[" << currentState << ']' << endl;
            SKGTRACEL(20) << "Page diff =" << (currentState != oldState ? "TRUE" : "FALSE") << endl;
            return (currentState != oldState);
        }
    }
    return false;
}

void SKGTabPage::overwrite(bool iUserConfirmation)
{
    //Is this widget linked to a bookmark ?
    if (!m_bookmarkID.isEmpty()) {
        //Yes. Is state modified ?
        SKGNodeObject node(getDocument(), SKGServices::stringToInt(m_bookmarkID));
        if (node.exist()) {
            QStringList data = SKGServices::splitCSVLine(node.getData());
            QString fullname = node.getFullName();
            if (data.count() > 2) {
                QString currentState = getState().trimmed();
                QString oldState = data[2].trimmed();
                currentState.remove('\n');
                oldState.remove('\n');
                SKGTRACEL(20) << "oldState      =[" << oldState << ']' << endl;
                SKGTRACEL(20) << "currentState  =[" << currentState << ']' << endl;
                if (currentState != oldState) {
                    QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
                    int conf = KMessageBox::Yes;
                    if (iUserConfirmation && !oldState.isEmpty()) conf = KMessageBox::questionYesNo(this,
                                i18nc("Question", "Bookmark '%1' has been modified. Do you want to update it with the current state?", fullname),
                                i18nc("Question", "Bookmark has been modified"),
                                KStandardGuiItem::yes(),
                                KStandardGuiItem::no(),
                                QString("updateBookmarkOnClose"));
                    QApplication::restoreOverrideCursor();
                    if (conf == KMessageBox::Yes) {
                        SKGError err;
                        {
                            SKGBEGINLIGHTTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Bookmark update '%1'", fullname), err);
                            data[2] = currentState;
                            if (!err) err = node.setData(SKGServices::stringsToCsv(data));
                            if (!err) err = node.save();
                        }
                        if (!err) err = SKGError(0, i18nc("Successful message after an user action", "Bookmark updated"));
                        SKGMainPanel::displayErrorMessage(err);
                    }
                }
            }
        }
    } else {
        //No. It is a page opened from context or from another page
        QString name = getDefaultStateAttribute();
        if (!name.isEmpty()) {
            QString currentState = getState().trimmed();
            QString oldState = getDocument()->getParameter(name);
            SKGTRACEL(20) << "oldState      =[" << oldState << ']' << endl;
            SKGTRACEL(20) << "currentState  =[" << currentState << ']' << endl;
            currentState.remove('\n');
            oldState.remove('\n');
            if (currentState != oldState) {
                QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
                int conf = KMessageBox::Yes;
                if (iUserConfirmation && !oldState.isEmpty()) conf = KMessageBox::questionYesNo(this,
                            i18nc("Question", "Page has been modified. Do you want to update it with the current state?"),
                            i18nc("Question", "Page has been modified"),
                            KStandardGuiItem::yes(),
                            KStandardGuiItem::no(),
                            QString("updateContextOnClose"));
                QApplication::restoreOverrideCursor();
                if (conf == KMessageBox::Yes) {
                    SKGError err;
                    {
                        SKGBEGINLIGHTTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Save default state"), err);
                        err = getDocument()->setParameter(name, currentState);
                    }
                    if (!err) err = SKGError(0, i18nc("Successful message after an user action", "Default state saved"));
                    SKGMainPanel::displayErrorMessage(err);
                }
            }
        }
    }
}


bool SKGTabPage::isEditor()
{
    return false;
}

void SKGTabPage::activateEditor() {}

QWidget* SKGTabPage::zoomableWidget() const
{
    return mainWidget();
}

QList< QWidget* > SKGTabPage::printableWidgets() const
{
    QList< QWidget* > output;
    output.push_back(mainWidget());
    return output;
}

bool SKGTabPage::isZoomable() const
{
    return (zoomableWidget() != NULL);
}

void SKGTabPage::setZoomPosition(int iValue)
{
    QWidget* widget = zoomableWidget();
    SKGTreeView* treeView = qobject_cast<SKGTreeView*>(widget);
    if (treeView) treeView->setZoomPosition(iValue);
    else {
        QWebView* webView = qobject_cast<QWebView*>(widget);
        if (webView) {
            webView->setZoomFactor(qPow(10, ((qreal) iValue) / 30.0));
        } else if (widget) {
            QFont font = widget->font();
            font.setPointSize(qMax(1, m_fontOriginalPointSize + iValue));
            widget->setFont(font);
        }
    }
}

int SKGTabPage::zoomPosition() const
{
    QWidget* widget = zoomableWidget();
    SKGTreeView* treeView = qobject_cast<SKGTreeView*>(widget);
    if (treeView) return treeView->zoomPosition();
    else {
        QWebView* webView = qobject_cast<QWebView*>(widget);
        if (webView) return qRound(30.0 * log10(webView->zoomFactor()));
        else if (widget) return widget->font().pointSize() - m_fontOriginalPointSize;
    }
    return 0;
}

SKGTabPage* SKGTabPage::parentTabPage(QWidget* iWidget)
{
    SKGTabPage* output = qobject_cast< SKGTabPage* >(iWidget);
    if (!output && iWidget) {
        QWidget* parent = iWidget->parentWidget();
        if (parent)  output = SKGTabPage::parentTabPage(parent);
    }

    return output;
}

#include "skgtabpage.moc"
