//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/Model/Sample/LayerItem.cpp
//! @brief     Implements class LayerItem.
//!
//! @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/Sample/LayerItem.h"
#include "Base/Util/Assert.h"
#include "Base/Util/Vec.h"
#include "GUI/Model/Sample/CompoundItem.h"
#include "GUI/Model/Sample/CoreAndShellItem.h"
#include "GUI/Model/Sample/MesocrystalItem.h"
#include "GUI/Model/Sample/ParticleItem.h"
#include "GUI/Model/Sample/ParticleLayoutItem.h"
#include "GUI/Model/Sample/SampleItem.h"
#include "GUI/Model/Util/UtilXML.h"

namespace {
namespace Tag {

const QString Name("Name");
const QString Color("Color");
const QString MaterialData("MaterialData");
const QString NumSlices("NumSlices");
const QString Thickness("Thickness");
const QString Roughness("Roughness");
const QString Layout("Layout");
const QString ExpandLayerGroupbox("ExpandLayerGroupbox");

} // namespace Tag

std::vector<ItemWithMaterial*> layoutItemsWithMaterial(ParticleLayoutItem* layout)
{
    std::vector<ItemWithMaterial*> result;

    std::vector<ItemWithParticles*> itemsWithParticles = layout->itemsWithParticles();
    while (!itemsWithParticles.empty()) {
        auto* item = itemsWithParticles.front();
        itemsWithParticles.erase(itemsWithParticles.begin());
        if (!item)
            continue;

        if (auto* p = dynamic_cast<CompoundItem*>(item))
            Vec::concat(itemsWithParticles, p->itemsWithParticles());
        else if (auto* p = dynamic_cast<MesocrystalItem*>(item))
            itemsWithParticles.push_back(p->basisItem());
        else if (auto* p = dynamic_cast<ParticleItem*>(item))
            result.push_back(p);
        else if (auto* p = dynamic_cast<CoreAndShellItem*>(item)) {
            if (p->coreItem())
                result.push_back(p->coreItem());
            if (p->shellItem())
                result.push_back(p->shellItem());
        } else
            ASSERT_NEVER;
    }
    return result;
}

} // namespace


LayerItem::LayerItem(const MaterialsSet* materials)
    : ItemWithMaterial(materials)
{
    m_thickness.init("Thickness (nm)", "Thickness of the layer", 0.0, 3,
                     RealLimits::lowerLimited(0.0), "thickness");

    m_roughness.initWithArgs("Top roughness", "Roughness of top interface",
                             RoughnessItemCatalog::Type::Basic);
}

LayerItem::~LayerItem() = default;

std::vector<ItemWithMaterial*> LayerItem::itemsWithMaterial()
{
    std::vector<ItemWithMaterial*> result;
    result.push_back(this);
    for (ParticleLayoutItem* layout : layoutItems())
        Vec::concat(result, layoutItemsWithMaterial(layout));
    return result;
}

std::vector<ItemWithParticles*> LayerItem::itemsWithParticles() const
{
    std::vector<ItemWithParticles*> result;
    for (auto* layout : layoutItems())
        Vec::concat(result, layout->containedItemsWithParticles());
    return result;
}

void LayerItem::setBasicRoughness()
{
    m_roughness.setCertainItem(new BasicRoughnessItem);
}

void LayerItem::clearRoughness()
{
    m_roughness.setCertainItem(nullptr);
}

ParticleLayoutItem* LayerItem::addLayoutItem()
{
    m_layouts.push_back(new ParticleLayoutItem(m_materials));
    return m_layouts.back();
}

void LayerItem::removeLayoutItem(ParticleLayoutItem* layout)
{
    m_layouts.delete_element(layout);
}

void LayerItem::writeTo(QXmlStreamWriter* w) const
{
    XML::writeAttribute(w, XML::Attrib::version, uint(1));

    // material data
    w->writeStartElement(Tag::MaterialData);
    ItemWithMaterial::writeTo(w);
    w->writeEndElement();

    // color
    w->writeStartElement(Tag::Color);
    XML::writeAttribute(w, XML::Attrib::value, m_color);
    w->writeEndElement();

    // number of slices
    w->writeStartElement(Tag::NumSlices);
    XML::writeAttribute(w, XML::Attrib::value, m_num_slices);
    w->writeEndElement();

    // thickness
    w->writeStartElement(Tag::Thickness);
    m_thickness.writeTo(w);
    w->writeEndElement();

    // roughness
    w->writeStartElement(Tag::Roughness);
    m_roughness.writeTo(w);
    w->writeEndElement();

    // particle layouts
    for (const auto* layout : m_layouts) {
        w->writeStartElement(Tag::Layout);
        layout->writeTo(w);
        w->writeEndElement();
    }

    // layer groupbox: is expanded?
    w->writeStartElement(Tag::ExpandLayerGroupbox);
    XML::writeAttribute(w, XML::Attrib::value, expandLayer);
    w->writeEndElement();
}

void LayerItem::readFrom(QXmlStreamReader* r)
{
    m_layouts.clear();

    const uint version = XML::readUIntAttribute(r, XML::Attrib::version);
    Q_UNUSED(version)

    while (r->readNextStartElement()) {
        QString tag = r->name().toString();

        // material data
        if (tag == Tag::MaterialData) {
            ItemWithMaterial::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // color
        } else if (tag == Tag::Color) {
            XML::readAttribute(r, XML::Attrib::value, &m_color);
            XML::gotoEndElementOfTag(r, tag);

            // number of slices
        } else if (tag == Tag::NumSlices) {
            XML::readAttribute(r, XML::Attrib::value, &m_num_slices);
            XML::gotoEndElementOfTag(r, tag);

            // thickness
        } else if (tag == Tag::Thickness) {
            m_thickness.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // roughness
        } else if (tag == Tag::Roughness) {
            m_roughness.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // particle layout
        } else if (tag == Tag::Layout) {
            addLayoutItem()->readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // layer groupbox: is expanded?
        } else if (tag == Tag::ExpandLayerGroupbox) {
            XML::readAttribute(r, XML::Attrib::value, &expandLayer);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}
