//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Material/MaterialsSet.cpp
//! @brief     Implements class MaterialsSet.
//!
//! @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/Material/MaterialsSet.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Material/MaterialItem.h"
#include "GUI/Model/Util/UtilXML.h"
#include <QColor>
#include <random>

namespace {

namespace Tag {

const QString Material("Material");

} // namespace Tag

QColor suggestMaterialColor(const QString& name)
{
    if (name.contains(materialMap.key(DefaultMaterials::Vacuum)))
        return {179, 242, 255};
    if (name.contains(materialMap.key(DefaultMaterials::Substrate)))
        return {205, 102, 0};
    if (name.contains(materialMap.key(DefaultMaterials::Default)))
        return QColor(Qt::green);
    if (name.contains(materialMap.key(DefaultMaterials::Core)))
        return {220, 140, 220};
    if (name.contains(materialMap.key(DefaultMaterials::Particle)))
        return {146, 198, 255};

    // return a random color
    static std::random_device r;
    std::mt19937 re(r());
    std::uniform_int_distribution<int> ru(0, 255);

    return QColor(ru(re), ru(re), ru(re));
}

} // namespace


const QMap<QString, DefaultMaterials> materialMap = {{"Default", DefaultMaterials::Default},
                                                     {"Vacuum", DefaultMaterials::Vacuum},
                                                     {"Particle", DefaultMaterials::Particle},
                                                     {"Core", DefaultMaterials::Core},
                                                     {"Substrate", DefaultMaterials::Substrate}};

MaterialsSet::MaterialsSet() = default;
MaterialsSet::~MaterialsSet() = default;

MaterialItem* MaterialsSet::addMaterialItem(MaterialItem* materialItem)
{
    return addMaterialItem(materialItem, true);
}

MaterialItem* MaterialsSet::addMaterialItem()
{
    return addMaterialItem(new MaterialItem, false);
}

MaterialItem* MaterialsSet::addMaterialItem(MaterialItem* materialItem, bool signalAdding)
{
    ASSERT(materialItem);
    materialItem->disconnect(this);
    push_back(materialItem);
    connect(materialItem, &MaterialItem::dataChanged, [this] { emit materialChanged(); });

    if (signalAdding)
        emit materialAddedOrRemoved();

    return materialItem;
}

MaterialItem* MaterialsSet::addRefractiveMaterialItem(const QString& name, double delta,
                                                      double beta)
{
    auto* materialItem = new MaterialItem;
    materialItem->setMatItemName(name);
    materialItem->setColor(suggestMaterialColor(name));
    materialItem->setRefractiveIndex(delta, beta);
    addMaterialItem(materialItem);

    return materialItem;
}

MaterialItem* MaterialsSet::addSLDMaterialItem(const QString& name, double sld, double abs_term)
{
    auto* materialItem = new MaterialItem;
    materialItem->setMatItemName(name);
    materialItem->setColor(suggestMaterialColor(name));
    materialItem->setScatteringLengthDensity(complex_t(sld, abs_term));
    addMaterialItem(materialItem);

    return materialItem;
}

MaterialItem* MaterialsSet::materialItemFromName(const QString& name) const
{
    for (auto* materialItem : *this)
        if (materialItem->matItemName() == name)
            return materialItem;
    return nullptr;
}

MaterialItem* MaterialsSet::materialItemFromIdentifier(const QString& identifier) const
{
    for (auto* materialItem : *this)
        if (materialItem->identifier() == identifier)
            return materialItem;
    return nullptr;
}

const MaterialItem* MaterialsSet::defaultMaterialItem() const
{
    ASSERT(!empty());
    return front();
}

const MaterialItem* MaterialsSet::defaultCoreMaterialItem() const
{
    for (auto* material : *this)
        if (material->matItemName() == materialMap.key(DefaultMaterials::Core))
            return material;
    return defaultMaterialItem();
}

const MaterialItem* MaterialsSet::defaultParticleMaterialItem() const
{
    for (auto* material : *this)
        if (material->matItemName() == materialMap.key(DefaultMaterials::Particle))
            return material;

    return defaultMaterialItem();
}

void MaterialsSet::removeMaterialItem(MaterialItem* materialItem)
{
    delete_element(materialItem);
    emit materialAddedOrRemoved();
}

void MaterialsSet::writeTo(QXmlStreamWriter* w) const
{
    // materials
    for (const auto* material : *this) {
        XML::writeTaggedElement(w, Tag::Material, *material);
    }
}

void MaterialsSet::readFrom(QXmlStreamReader* r)
{
    clear();
    while (r->readNextStartElement()) {
        QString tag = r->name().toString();
        if (tag == Tag::Material) {
            addMaterialItem()->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}
