//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Resample/Coherence/CoheringSubparticles.cpp
//! @brief     Implements class CoheringSubparticles.
//!
//! @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 "Resample/Coherence/CoheringSubparticles.h"
#include "Base/Spin/SpinMatrix.h"
#include "Resample/Particle/IReParticle.h"
#include <utility>

struct SubparticlePlacements {
    const IReParticle* subparticle;
    std::vector<R3> shifts;
};

CoheringSubparticles::~CoheringSubparticles() = default;

CoheringSubparticles::CoheringSubparticles(double abundance, OwningVector<IReParticle>&& terms)
    : m_abundance(abundance)
    , m_subparticles(std::move(terms))
{
    findUniqueSubparticles();
}

complex_t CoheringSubparticles::summedFF(const DiffuseElement& ele) const
{
    complex_t result = 0.;
    for (const auto& unique : m_unique_subparticles) {
        const auto& components = unique.subparticle->calcCoherentComponents(ele);
        for (const auto& shift : unique.shifts)
            result += unique.subparticle->coherentFF(components, shift);
    }
    return result;
}

SpinMatrix CoheringSubparticles::summedPolFF(const DiffuseElement& ele) const
{
    SpinMatrix result;
    for (const auto& unique : m_unique_subparticles) {
        const auto& components = unique.subparticle->calcCoherentPolComponents(ele);
        for (const auto& shift : unique.shifts)
            result += unique.subparticle->coherentPolFF(components, shift);
    }
    return result;
}

double CoheringSubparticles::radialExtension() const
{
    return m_subparticles[0]->radialExtension();
}

void CoheringSubparticles::findUniqueSubparticles()
{
    std::vector<bool> is_excluded(m_subparticles.size(), false);
    for (size_t i = 0; i < m_subparticles.size(); i++) {
        if (is_excluded[i])
            continue;

        m_unique_subparticles.push_back({m_subparticles[i], {R3()}});
        const R3* unique_pos = m_subparticles[i]->position();

        for (size_t k = i + 1; k < m_subparticles.size(); k++)
            if (!is_excluded[k] && m_subparticles[k]->consideredEqualTo(*m_subparticles[i])) {
                const R3* other_pos = m_subparticles[k]->position();
                m_unique_subparticles.back().shifts.push_back(
                    IReParticle::posDiff(other_pos, unique_pos));
                is_excluded[k] = true;
            }
    }
}
