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

namespace {
namespace Tag {

const QString OwnDensity("OwnDensity");
const QString InterferenceFunction("InterferenceFunction");
const QString Particle("Particle");
const QString ExpandLayoutGroupbox("ExpandLayoutGroupbox");
const QString ExpandInterferenceGroupbox("ExpandInterferenceGroupbox");

} // namespace Tag
} // namespace

ParticleLayoutItem::ParticleLayoutItem(const MaterialsSet* materials)
    : m_materials(materials)
{
    m_own_density.init("Total particle density (nm^-2)",
                       "Number of particles per area (particle surface density).\n "
                       "Should be defined for disordered and 1d-ordered particle collections.",
                       0.0005, 6, 0.0001 /* step */, RealLimits::nonnegative(), "density");

    m_interference.initWithArgs("Interference function", "", InterferenceItemCatalog::Type::None);
}

double ParticleLayoutItem::totalDensityValue() const
{
    if (!totalDensityIsDefinedByInterference())
        return m_own_density.value();

    ASSERT(m_interference.certainItem());

    if (const auto* interLatticeItem =
            dynamic_cast<const Interference2DAbstractLatticeItem*>(m_interference.certainItem())) {
        Lattice2DItem* latticeItem = interLatticeItem->latticeTypeItem();
        try {
            const double area = latticeItem->unitCellArea();
            return area == 0.0 ? 0.0 : 1.0 / area;
        } catch (const std::exception&) {
            // nothing to do here; new exception will be caught during job execution
            return 0.0;
        }
    }

    if (const auto* hd =
            dynamic_cast<const InterferenceHardDiskItem*>(m_interference.certainItem()))
        return hd->density();

    ASSERT_NEVER;
}

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

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

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

const PolyItem<InterferenceItemCatalog>& ParticleLayoutItem::interferenceSelection() const
{
    return m_interference;
}

bool ParticleLayoutItem::totalDensityIsDefinedByInterference() const
{
    return dynamic_cast<const Interference2DAbstractLatticeItem*>(m_interference.certainItem())
           || dynamic_cast<const InterferenceHardDiskItem*>(m_interference.certainItem());
}

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

    // own density
    w->writeStartElement(Tag::OwnDensity);
    m_own_density.writeTo(w);
    w->writeEndElement();

    // interference function
    w->writeStartElement(Tag::InterferenceFunction);
    m_interference.writeTo(w);
    w->writeEndElement();

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

    // layout groupbox: is expanded?
    w->writeStartElement(Tag::ExpandLayoutGroupbox);
    XML::writeAttribute(w, XML::Attrib::value, expandParticleLayout);
    w->writeEndElement();

    // interference groupbox: is expanded?
    w->writeStartElement(Tag::ExpandInterferenceGroupbox);
    XML::writeAttribute(w, XML::Attrib::value, expandInterference);
    w->writeEndElement();
}

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

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

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

        // own density
        if (tag == Tag::OwnDensity) {
            m_own_density.readFrom(r);
            XML::gotoEndElementOfTag(r, tag);

            // interference function
        } else if (tag == Tag::InterferenceFunction) {
            m_interference.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);

            // layout groupbox: is expanded?
        } else if (tag == Tag::ExpandLayoutGroupbox) {
            expandParticleLayout = XML::readBool(r, XML::Attrib::value);
            XML::gotoEndElementOfTag(r, tag);

            // interference groupbox: is expanded?
        } else if (tag == Tag::ExpandInterferenceGroupbox) {
            expandInterference = XML::readBool(r, XML::Attrib::value);
            XML::gotoEndElementOfTag(r, tag);

        } else
            r->skipCurrentElement();
    }
}
