//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Common/DataPropertyWidget.cpp
//! @brief     Defines class DataPropertyWidget
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2022
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Common/DataPropertyWidget.h"
#include "Base/Util/Assert.h"
#include "Device/Coord/ICoordSystem.h"
#include "GUI/Model/Data/DataItem.h"
#include "GUI/Model/Data/DataItemUtil.h"
#include "GUI/Model/Device/InstrumentItems.h"
#include "GUI/Model/Project/ProjectDocument.h"
#include "GUI/Support/Util/CoordName.h"
#include <QFormLayout>

DataPropertyWidget::DataPropertyWidget(QWidget* parent)
    : DataAccessWidget(parent)
{
    setWindowTitle("Properties");

    m_mainLayout = new QFormLayout(this);
    m_mainLayout->setContentsMargins(8, 20, 8, 8);
    m_mainLayout->setSpacing(5);
}

void DataPropertyWidget::setJobOrRealItem(QObject* job_or_real_Item)
{
    DataAccessWidget::setJobOrRealItem(job_or_real_Item);
    createPanelElements();
}

void DataPropertyWidget::updateItemCoords(DataItem* item)
{
    if (!item)
        return;

    if (instrumentItem()) {
        item->blockSignals(true);
        const auto converter = instrumentItem()->createCoordSystem();
        item->updateCoords(*converter);
        item->blockSignals(false);
        emit item->axesUnitsReplotRequested();
    }

    updateUIValues();
}

void DataPropertyWidget::updateUIValues()
{
    if (jobRealBase())
        for (const auto& updater : m_updaters)
            updater();
}

InstrumentItem* DataPropertyWidget::instrumentItem()
{
    if (jobItem())
        return jobItem()->instrumentItem();
    else if (realItem()) {
        ASSERT(gProjectDocument.has_value());
        return gProjectDocument.value()->instrumentModel()->findInstrumentItemById(
            realItem()->instrumentId());
    } else
        ASSERT(false);
    return nullptr;
}

QStringList DataPropertyWidget::axesUnitsList()
{
    QStringList list;
    if (!instrumentItem()) {
        ASSERT(realItem());
        list << realItem()->dataItem()->currentAxesUnits();
    } else {
        const auto converter = instrumentItem()->createCoordSystem();
        ASSERT(converter);
        list = GUI::Model::DataItemUtil::availableUnits(*converter);
    }
    return list;
}
