/***************************************************************************
 *   Copyright (C) 2020 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 <https://www.gnu.org/licenses/>  *
 ***************************************************************************/
/** @file
 * This file defines classes SKGNamedObject.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgnamedobject.h"
#include "skgdocument.h"

SKGNamedObject::SKGNamedObject() : SKGNamedObject(nullptr)
{}

SKGNamedObject::SKGNamedObject(SKGDocument* iDocument, const QString& iTable, int iID) : SKGObjectBase(iDocument, iTable, iID)
{}

SKGNamedObject::SKGNamedObject(const SKGNamedObject& iObject) = default;

SKGNamedObject::SKGNamedObject(const SKGObjectBase& iObject) : SKGObjectBase(iObject)
{}

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

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

SKGNamedObject::~SKGNamedObject()
    = default;

SKGError SKGNamedObject::setName(const QString& iName)
{
    return setAttribute(QStringLiteral("t_name"), iName);
}

QString SKGNamedObject::getName() const
{
    return getAttribute(QStringLiteral("t_name"));
}

QString SKGNamedObject::getWhereclauseId() const
{
    // Could we use the id
    QString output = SKGObjectBase::getWhereclauseId();
    if (output.isEmpty()) {
        // No, so we use the name
        QString name = SKGServices::stringToSqlString(getName());
        if (!name.isEmpty() || getID() == 0) {
            output = "t_name='" % name % '\'';
        }
    }
    return output;
}

SKGError SKGNamedObject::getObjectByName(SKGDocument* iDocument, const QString& iTable, const QString& iName, SKGObjectBase& oObject)
{
    return iDocument != nullptr ? iDocument->getObject(iTable, "t_name='" % SKGServices::stringToSqlString(iName) % '\'', oObject) : SKGError();
}
