/***************************************************************************
 *   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 implements classes SKGNodeObject.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgnodeobject.h"

#include <klocalizedstring.h>
#include <QIcon>

#include "skgtraces.h"
#include "skgdefine.h"
#include "skgdocument.h"

SKGNodeObject::SKGNodeObject(SKGDocument* iDocument, int iID): SKGNamedObject(iDocument, "v_node", iID)
{
}

SKGNodeObject::~SKGNodeObject()
{
}

SKGNodeObject::SKGNodeObject(const SKGNodeObject& iObject)
    : SKGNamedObject(iObject)
{
}
SKGNodeObject::SKGNodeObject(const SKGObjectBase& iObject)
    : SKGNamedObject(iObject.getDocument(), "v_node", iObject.getID())
{
}

const SKGNodeObject& SKGNodeObject::operator= (const SKGObjectBase& iObject)
{
    copyFrom(iObject);
    return *this;
}

SKGError SKGNodeObject::setName(const QString& iName)
{
    SKGError err;
    if (iName.contains(OBJECTSEPARATOR)) {
        err = SKGError(ERR_FAIL, i18nc("Error message: an invalid character was found", "The name '%1' is invalid : the '%2' character is forbidden ", iName, QString(OBJECTSEPARATOR)));
    } else {
        err = SKGNamedObject::setName(iName);
    }
    return err;
}

QString SKGNodeObject::getWhereclauseId() const
{
    // Could we use the id
    QString output = SKGObjectBase::getWhereclauseId();
    if (output.isEmpty()) {
        if (!(getAttribute("t_name").isEmpty())) {
            output = "t_name='" % SKGServices::stringToSqlString(getAttribute("t_name")) % '\'';
        }
        QString rd_node_id = getAttribute("rd_node_id");
        if (!output.isEmpty()) {
            output += " AND ";
        }
        if (rd_node_id.isEmpty()) {
            output += "(rd_node_id=0 OR rd_node_id IS NULL OR rd_node_id='')";
        } else {
            output += "rd_node_id=" % rd_node_id;
        }
    }
    return output;
}

QString SKGNodeObject::getFullName() const
{
    return getAttribute("t_fullname");
}

SKGError SKGNodeObject::setData(const QString& iData)
{
    return setAttribute("t_data", iData);
}

QString SKGNodeObject::getData() const
{
    return getAttribute("t_data");
}

bool SKGNodeObject::isFolder() const
{
    return getData().isEmpty();
}

SKGError SKGNodeObject::setIcon(const QString& iIcon)
{
    return setAttribute("t_icon", iIcon);
}

QIcon SKGNodeObject::getIcon() const
{
    QStringList overlay;
    if (isAutoStart()) {
        overlay.push_back("user-online");
    }
    return SKGServices::fromTheme(getAttribute("t_icon") , overlay);
}

SKGError SKGNodeObject::setAutoStart(bool iAutoStart)
{
    return setAttribute("t_autostart", iAutoStart ? "Y" : "N");
}

bool SKGNodeObject::isAutoStart() const
{
    return (getAttribute("t_autostart") == "Y");
}

SKGError SKGNodeObject::setOrder(double iOrder)
{
    SKGError err;
    double order = iOrder;
    if (order == -1) {
        order = 1;
        SKGStringListList result;
        err = getDocument()->executeSelectSqliteOrder("SELECT max(f_sortorder) from node", result);
        if (!err && result.count() == 2) {
            order = SKGServices::stringToDouble(result.at(1).at(0)) + 1;
        }
    }
    IFOKDO(err, setAttribute("f_sortorder", SKGServices::doubleToString(order)))
    return err;
}

double SKGNodeObject::getOrder() const
{
    return SKGServices::stringToDouble(getAttribute("f_sortorder"));
}

SKGError SKGNodeObject::createPathNode(SKGDocument* iDocument,
                                       const QString& iFullPath,
                                       SKGNodeObject& oNode,
                                       bool iRenameIfAlreadyExist)
{
    SKGError err;
    SKGTRACEINFUNCRC(10, err);
    SKGTRACEL(10) << "Input parameter [iFullPath]=" << iFullPath << endl;
    // Check if node is already existing
    if (!iRenameIfAlreadyExist && iDocument) {
        iDocument->getObject("v_node", "t_fullname='" % SKGServices::stringToSqlString(iFullPath) % '\'', oNode);
    }
    if (oNode.getID() == 0) {
        // No, we have to create it
        // Search node separator
        int posSeparator = iFullPath.lastIndexOf(OBJECTSEPARATOR);
        if (posSeparator == -1) {
            oNode = SKGNodeObject(iDocument);
            err = oNode.setName(iFullPath);

            // Check if already existing
            if (!err && iRenameIfAlreadyExist) {
                int index = 1;
                while (!err && oNode.exist()) {
                    index++;
                    err = oNode.setName(iFullPath % " (" % SKGServices::intToString(index) % ')');
                }
            }

            IFOKDO(err, oNode.setIcon("folder-bookmark"))
            IFOKDO(err, oNode.setOrder(-1))
            IFOKDO(err, oNode.save())
        } else {
            // Get first and second parts of the branch
            QString first = iFullPath.mid(0, posSeparator);
            QString second = iFullPath.mid(posSeparator + QString(OBJECTSEPARATOR).length(), iFullPath.length() - posSeparator - QString(OBJECTSEPARATOR).length());

            // Get first node
            SKGNodeObject FirstNode;
            err = SKGNodeObject::createPathNode(iDocument, first, FirstNode);

            IFOK(err) {
                // Get second node
                err = FirstNode.addNode(oNode);

                // Add second under first
                IFOKDO(err, oNode.setName(second))

                // Check if already existing
                if (!err && iRenameIfAlreadyExist) {
                    int index = 2;
                    while (!err && oNode.exist()) {
                        err = oNode.setName(second % " (" % SKGServices::intToString(index) % ')');
                        ++index;
                    }
                }

                // save
                IFOKDO(err, oNode.setIcon("folder-bookmark"))
                IFOKDO(err, oNode.setOrder(-1))
                IFOKDO(err, oNode.save())
            }
        }
    }

    return err;
}

SKGError SKGNodeObject::addNode(SKGNodeObject& oNode)
{
    SKGError err;
    SKGTRACEINFUNCRC(10, err);
    if (getID() == 0) {
        err = SKGError(ERR_FAIL, i18nc("Error message: Something failed because of a database issue", "%1 failed because linked object is not yet saved in the database.", QString("SKGNodeObject::addNode")));
    } else {
        oNode = SKGNodeObject(getDocument());
        err = oNode.setAttribute("rd_node_id", SKGServices::intToString(getID()));
    }
    return err;
}

SKGError SKGNodeObject::removeParentNode()
{
    return setAttribute("rd_node_id", "");
}

SKGError SKGNodeObject::setParentNode(const SKGNodeObject& iNode)
{
    SKGError err;
    SKGTRACEINFUNCRC(10, err);
    if (iNode.getID() == 0) {
        err = SKGError(ERR_FAIL, i18nc("Error message: Something failed because of a database issue", "%1 failed because linked object is not yet saved in the database.", QString("SKGNodeObject::setParentNode")));
    } else {
        // Check if it's a loop
        SKGNodeObject current = iNode;
        do {
            if (current == *this) {
                err = SKGError(ERR_FAIL, i18nc("Error message: Loops are forbidden in Skrooge data structures", "You cannot create a loop, ie parent and child with the same name. For example, A > A is a loop. A > B > A is another kind of loop"));
            } else {
                SKGNodeObject parentNode;
                current.getParentNode(parentNode);
                current = parentNode;
            }
        } while (!err && current.getID() != 0);

        IFOKDO(err, setAttribute("rd_node_id", SKGServices::intToString(iNode.getID())))
    }
    return err;
}

SKGError SKGNodeObject::getParentNode(SKGNodeObject& oNode) const
{
    SKGError err;
    QString parent_id = getAttribute("rd_node_id");
    if (!parent_id.isEmpty()) {
        err = getDocument()->getObject("v_node", "id=" % parent_id , oNode);
    } else {
        oNode = SKGNodeObject();
    }
    return err;
}

SKGError SKGNodeObject::getNodes(SKGListSKGObjectBase& oNodeList) const
{
    return getDocument()->getObjects("v_node", "rd_node_id=" % SKGServices::intToString(getID()) % " ORDER BY f_sortorder, t_name", oNodeList);
}


