//  ************************************************************************************************
//
//  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/Model/Util/UtilXML.h"
#include <QDir>

class Datafield;
class DatafileItem;
class DatafilesSet;

namespace UTest::GUI {

//! 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 1D output data array of custom size
Datafield makeData1D(double value, int nx = 5, double x_min = -1.0, double x_max = 1.0);

//! Creates 2D output data array of custom size
Datafield makeData2D(double value, int nx = 5, double x_min = -1.0, double x_max = 1.0, int ny = 10,
                     double y_min = 0.0, double y_max = 2.0);

//! Creates real 1D data item initialized with Datafield
DatafileItem* createRealData1D(const QString& name, DatafilesSet& set, double value);

//! Creates real 2D data item initialized with Datafield
DatafileItem* createRealData2D(const QString& name, DatafilesSet& set, double value);

//! 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().toStdString() + "' differs from '"
                                 + tag.toStdString() + "' in file '" + path.toStdString() + "'");

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

#endif // BORNAGAIN_TESTS_UNIT_GUI_UTILS_H
