//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Data/DataItemUtil.cpp
//! @brief     Implements class DataItemUtils
//!
//! @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 "GUI/Model/Data/DataItemUtil.h"
#include "Base/Util/Assert.h"
#include "Device/Coord/ICoordSystem.h"
#include "Device/Data/Datafield.h"
#include "Device/Histo/SimulationResult.h"
#include "GUI/Model/Data/DataItem.h"
#include "GUI/Support/Util/CoordName.h"

void GUI::Model::DataItemUtil::updateAxesTitle(DataItem* intensityItem,
                                               const ICoordSystem& converter, Coords units)
{
    intensityItem->setXaxisTitle(QString::fromStdString(converter.nameOfAxis(0, units)));
    if (converter.rank() > 1)
        intensityItem->setYaxisTitle(QString::fromStdString(converter.nameOfAxis(1, units)));
}

QStringList GUI::Model::DataItemUtil::availableUnits(const ICoordSystem& converter)
{
    QStringList result;
    for (auto units : converter.availableUnits()) {
        auto unit_name = GUI::Util::CoordName::nameFromCoord(units);
        if (!unit_name.isEmpty())
            result << unit_name;
    }
    return result;
}

//! Updates axes of Datafield in IntensityData item to correspond with axes units selection.
//! InstrumentItem is used to get domain's detector map for given units.

void GUI::Model::DataItemUtil::updateDataAxes(DataItem* dataItem, const ICoordSystem& converter)
{
    ASSERT(dataItem);
    const Datafield* oldData = dataItem->c_field();
    if (!oldData)
        return;

    Coords axes_units = dataItem->currentCoord();

    auto newData = std::make_unique<Datafield>(converter.convertedAxes(axes_units),
                                               oldData->flatVector(), oldData->errorSigmas());

    dataItem->setDatafield(newData.release());
    dataItem->setAxesRangeToData();
    updateAxesTitle(dataItem, converter, axes_units);
}

void GUI::Model::DataItemUtil::createDefaultDetectorMap(DataItem* dataItem,
                                                        const ICoordSystem& converter)
{
    auto current_coord = dataItem->currentCoord();
    auto output_data = std::make_unique<Datafield>(converter.convertedAxes(current_coord));
    dataItem->setDatafield(output_data.release());
    updateAxesTitle(dataItem, converter, current_coord);
}
