//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Util/Backup.h
//! @brief     Defines GUI::Util namespace.
//!
//! @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)
//
//  ************************************************************************************************

#ifndef BORNAGAIN_GUI_MODEL_UTIL_BACKUP_H
#define BORNAGAIN_GUI_MODEL_UTIL_BACKUP_H

#include "Base/Util/Assert.h"
#include <QXmlStreamReader>

namespace {
namespace Tag {

const QString Backup("Backup");

} // namespace Tag
} // namespace

namespace GUI::Util {

template <typename T> QByteArray createBackup(const T* t)
{
    QByteArray backup;
    QXmlStreamWriter w(&backup);
    w.writeStartElement(Tag::Backup);
    t->writeTo(&w);
    w.writeEndElement();
    return backup;
}

template <typename T> void restoreBackup(T* t, const QByteArray& backup)
{
    QXmlStreamReader r(backup);
    r.readNextStartElement();
    ASSERT(r.name().toString() == Tag::Backup);
    t->readFrom(&r);
}

template <typename T> void copyContents(const T* source, T* dest)
{
    GUI::Util::restoreBackup(dest, GUI::Util::createBackup(source));
}

} // namespace GUI::Util

#endif // BORNAGAIN_GUI_MODEL_UTIL_BACKUP_H
