//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Tests/Suite/XML/Check.cpp
//! @brief     Implements function checkSimulation for GUI/XML serialization standard test.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "BABuild.h"
#include "BATesting.h"
#include "Base/Util/PathUtil.h"
#include "Device/Data/Datafield.h"
#include "Device/IO/DiffUtil.h"
#include "Device/IO/IOFactory.h"
#include "GUI/Model/FromCore/ItemizeSample.h"
#include "GUI/Model/FromCore/ItemizeSimulation.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/Model/Sample/SamplesSet.h"
#include "GUI/Model/Sim/BackgroundItems.h"
#include "GUI/Model/Sim/InstrumentsSet.h"
#include "GUI/Model/Sim/SimulationOptionsItem.h"
#include "GUI/Model/ToCore/SimulationToCore.h"
#include "GUI/Model/Util/Backup.h"
#include "Sim/Simulation/ISimulation.h"
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

//! Run simulation directly (in core) and through GUI model reloaded from XML, and compare results.

bool checkSimulation(const std::string& test_name, ISimulation& sim, double precision, double snr,
                     int allowed_outliers)
{
    std::cout << "Tests/Suite/XML: " << test_name << std::endl;

    const auto dir = fs::path(BATesting::TestOutDir) / fs::path("Suite") / fs::path("xml");
    Base::Path::createDirectories(dir.string());
    const std::string output_path = (dir / fs::path(test_name + ".ba")).string();
    std::remove(output_path.c_str());
    std::cout << "- removed old output " << output_path << std::endl;

    QString fname = QString::fromStdString(output_path);

    std::cout << "  Store simulation as GUI/XML project file" << std::endl;
    std::unique_ptr<SimulationOptionsItem> optionsItem(GUI::FromCore::itemizeOptions(sim));
    ProjectDocument D;
    D.instrumentsRW()->add_item(GUI::FromCore::itemizeInstrument(sim));
    D.samplesRW()->add_item(GUI::FromCore::itemizeSample(*sim.sample()));
    GUI::Util::copyContents(optionsItem.get(), D.simulationOptionsRW());
    D.saveProjectFileWithData(fname);

    std::cout << "  Reload simulation from GUI/XML project file" << std::endl;
    ProjectDocument D2;
    D2.loadProjectFileWithData(fname);

    try {
        std::cout << "  Run simulation after round trip" << std::endl;
        std::unique_ptr<ISimulation> sim2(GUI::ToCore::itemsToSimulation(
            D2.samples()->at(0), D2.instruments()->at(0), D2.simulationOptionsItem()));
        const Datafield data2 = sim2->simulate();

        std::cout << "  Run direct simulation" << std::endl;
        const Datafield ref_data = sim.simulate();

        std::cout << "  Check difference" << std::endl;
        if (!DiffUtil::checkConsistence(data2, ref_data, precision, snr, allowed_outliers))
            throw std::runtime_error("simulation results differ");

    } catch (const std::exception& ex) {
        std::cout << "  Catched exception: " << ex.what() << std::endl;

        QString fname2 = fname + ".2";
        D2.saveProjectFileWithData(fname2);
        std::cout << "  Stored second project file (after round trip) in " << fname2.toStdString()
                  << std::endl;

        return false;
    }

    return true;
}
