//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Descriptor/VectorProperty.cpp
//! @brief     Implements class VectorProperty.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2021
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/Model/Descriptor/VectorProperty.h"
#include "GUI/Model/Util/UtilXML.h"
#include <QUuid>

namespace {
namespace Tag {

const QString X("X");
const QString Y("Y");
const QString Z("Z");

} // namespace Tag
} // namespace

void VectorProperty::init(const QString& label, const QString& tooltip, const QString& uidPrefix)
{
    init(label, tooltip, R3(), 3, 0.01, RealLimits::limitless(), uidPrefix);
}

void VectorProperty::init(const QString& label, const QString& tooltip, const R3& value,
                          uint decimals, double step, const RealLimits& limits,
                          const QString& uidPrefix)
{
    m_label = label;

    m_x.init("x", tooltip, value.x(), decimals, step, limits, uidPrefix);
    m_y.init("y", tooltip, value.y(), decimals, step, limits, uidPrefix);
    m_z.init("z", tooltip, value.z(), decimals, step, limits, uidPrefix);

    QString uid;
    if (uidPrefix.size() > 0)
        uid = uidPrefix + "/" + QUuid::createUuid().toString();
    else
        uid = QUuid::createUuid().toString();

    m_x.setUid(uid + "/x");
    m_y.setUid(uid + "/y");
    m_z.setUid(uid + "/z");
}

bool VectorProperty::operator==(const VectorProperty& other) const
{
    return (m_label == other.m_label) && (m_x.dVal() == other.m_x.dVal())
           && (m_y.dVal() == other.m_y.dVal()) && (m_z.dVal() == other.m_z.dVal());
}

void VectorProperty::writeTo(QXmlStreamWriter* w) const
{
    m_x.writeTo2(w, Tag::X);
    m_y.writeTo2(w, Tag::Y);
    m_z.writeTo2(w, Tag::Z);
}

void VectorProperty::readFrom(QXmlStreamReader* r)
{
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        if (tag == Tag::X)
            m_x.readFrom2(r, tag);
        else if (tag == Tag::Y)
            m_y.readFrom2(r, tag);
        else if (tag == Tag::Z)
            m_z.readFrom2(r, tag);
        else
            r->skipCurrentElement();
    }
}
