//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Tests/Unit/GUI/Utils.h
//! @brief     Defines auxiliary test functions in a namespace.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2015
//! @authors   Scientific Computing Group at MLZ Garching
//
//  ************************************************************************************************

#ifndef BORNAGAIN_TESTS_UNIT_GUI_UTILS_H
#define BORNAGAIN_TESTS_UNIT_GUI_UTILS_H

#include "GUI/Support/XML/UtilXML.h"
#include <QDir>

class Datafield;
class RealItem;
class RealModel;

namespace UTest::GUI {

enum class DIM { D1 = 1, D2 = 2 };

//! Creates directory in current working directory. If such directory already exists,
//! it will be removed with all its content.
void create_dir(const QString& dir_name);

//! Creates output data array for testing purposes
std::unique_ptr<Datafield> createData(double value = 0.0, DIM n_dim = DIM::D2);

//! Creates real data item initialized with Datafield for testing purposes
RealItem* createRealData(const QString& name, RealModel& model, double value = 0.0,
                         DIM n_dim = DIM::D2);

//! Helper function to test if data are the same.
bool isTheSame(const Datafield& data1, const Datafield& data2);

//! Helper function to check if file on disk represents same data.
bool isTheSame(const QString& fileName, const Datafield& data);

//! Exports class data to project file as XML data
template <typename T>
void writeXMLFile(QString path, const T& model, QString tag)
{
    // open file to write
    QFile file(path);
    file.open(QFile::WriteOnly | QIODevice::Truncate | QFile::Text);

    // write data to disk
    QXmlStreamWriter w(&file);
    w.writeStartElement(tag);
    w.setAutoFormatting(true);
    model.writeTo(&w);
    w.writeEndElement();
    file.close();
}

//! Imports class data from XML data of project file
template <typename T>
void readXMLFile(QString path, T& model, QString tag)
{
    // open file to read
    QFile file(path);
    file.open(QIODevice::ReadOnly | QIODevice::Text);

    // read data from disk
    QXmlStreamReader r(&file);
    r.readNextStartElement();

    if (r.name().toString() != tag)
        throw std::runtime_error("UTest::GUI::readXMLFile -> Error. The found tag '"
                                 + r.name().toString().toLatin1() + "' differs from '"
                                 + tag.toLatin1() + "' in file '" + path.toLatin1() + "'");

    model.readFrom(&r);
    XML::gotoEndElementOfTag(&r, r.name().toString());
    file.close();
}
} // namespace UTest::GUI

#endif // BORNAGAIN_TESTS_UNIT_GUI_UTILS_H
