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

#include "GUI/Model/Sample/CompoundItem.h"
#include "Base/Util/Assert.h"
#include "Base/Util/Vec.h"
#include "GUI/Model/Descriptor/PolyItem.h"
#include "GUI/Model/Sample/CoreAndShellItem.h"
#include "GUI/Model/Sample/MesocrystalItem.h"
#include "GUI/Model/Sample/ParticleItem.h"
#include "GUI/Model/Sample/ParticlesCatalog.h"
#include "Sample/Particle/CoreAndShell.h"
#include "Sample/Particle/Mesocrystal.h"
#include "Sample/Particle/Particle.h"
#include "Sample/Scattering/Rotations.h"

namespace {
namespace Tag {

const QString Particle("Particle");
const QString BaseData("BaseData");
const QString ExpandCompoundGroupbox("ExpandCompoundGroupbox");

} // namespace Tag

const QString abundance_tooltip = "Proportion of this type of particles normalized to the \n"
                                  "total number of particles in the layout";

const QString position_tooltip = "Relative position of the particle's reference point \n"
                                 "in the coordinate system of the parent (nm)";

} // namespace


CompoundItem::CompoundItem(const MaterialsSet* materials)
    : ItemWithParticles(abundance_tooltip, position_tooltip)
    , m_materials(materials)
{
    ASSERT(m_materials);
}

void CompoundItem::addItemWithParticleSelection(ItemWithParticles* particle)
{
    m_particles.push_back(particle);
}

void CompoundItem::removeItemWithParticle(ItemWithParticles* particle)
{
    m_particles.delete_element(particle);
}

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

    // parameters from base class
    w->writeStartElement(Tag::BaseData);
    ItemWithParticles::writeTo(w);
    w->writeEndElement();

    // particles
    for (auto* t : m_particles) {
        w->writeStartElement(Tag::Particle);
        PolyItem<ParticlesCatalog>::writeItemTo(t, w);
        w->writeEndElement();
    }

    // compound groupbox: is expanded?
    w->writeStartElement(Tag::ExpandCompoundGroupbox);
    XML::writeAttribute(w, XML::Attrib::value, expandCompound);
    w->writeEndElement();
}

void CompoundItem::readFrom(QXmlStreamReader* r)
{
    m_particles.clear();

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

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

        // parameters from base class
        if (tag == Tag::BaseData) {
            ItemWithParticles::readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // particle
        } else if (tag == Tag::Particle) {
            m_particles.push_back(PolyItem<ParticlesCatalog>().readItemFrom(r, m_materials));
            XML::gotoEndElementOfTag(r, tag);

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

        } else
            r->skipCurrentElement();
    }
}

std::unique_ptr<Compound> CompoundItem::createCompound() const
{
    auto P_composition = std::make_unique<Compound>();
    P_composition->setAbundance(abundance());
    for (ItemWithParticles* t : m_particles) {
        if (auto* particleItem = dynamic_cast<ParticleItem*>(t)) {
            if (auto P_particle = particleItem->createParticle())
                P_composition->addComponent(*P_particle);
        } else if (auto* coreShellItem = dynamic_cast<CoreAndShellItem*>(t)) {
            if (auto P_particle_coreshell = coreShellItem->createCoreAndShell())
                P_composition->addComponent(*P_particle_coreshell);
        } else if (auto* compositionItem = dynamic_cast<CompoundItem*>(t)) {
            if (auto P_child_composition = compositionItem->createCompound())
                P_composition->addComponent(*P_child_composition);
        } else if (auto* mesocrystalItem = dynamic_cast<MesocrystalItem*>(t)) {
            if (auto P_meso = mesocrystalItem->createMesocrystal())
                P_composition->addComponent(*P_meso);
        }
    }

    if (const auto r = createRotation(); r && !r->isIdentity())
        P_composition->rotate(*r);
    P_composition->translate(position());

    return P_composition;
}

std::vector<ItemWithParticles*> CompoundItem::containedItemsWithParticles() const
{
    std::vector<ItemWithParticles*> result;
    for (auto* t : m_particles) {
        result.push_back(t);
        Vec::concat(result, t->containedItemsWithParticles());
    }
    return result;
}
