//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Param/Distrib/DistributionHandler.cpp
//! @brief     Implements class DistributionHandler.
//!
//! @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 "Param/Distrib/DistributionHandler.h"
#include "Base/Util/Assert.h"
#include "Param/Distrib/Distributions.h"
#include "Param/Distrib/ParameterDistribution.h"
#include "Param/Distrib/ParameterSample.h"

DistributionHandler::DistributionHandler()
    : m_n_combinations(1)
{
}

DistributionHandler::~DistributionHandler() = default;

void DistributionHandler::addDistribution(const ParameterDistribution& par_distr)
{
    if (par_distr.nDraws() > 0) {
        m_distributions.push_back(par_distr);
        m_n_combinations *= par_distr.nDraws();
        m_cached_samples.push_back(par_distr.generateSamples());
    }
}

double DistributionHandler::setParameterValues(size_t index)
{
    ASSERT(index < m_n_combinations);

    size_t n_distr = m_distributions.size();
    double weight = 1.0;
    if (n_distr == 0)
        return weight;
    for (size_t param_index = n_distr - 1;; --param_index) {
        const auto& distribution = m_distributions[param_index];
        size_t remainder = index % distribution.nDraws();
        index /= distribution.nDraws();

        // set the value in the ISimulation instance (via callback)
        ASSERT(m_set_value_functions.count(&distribution) == 1);
        m_set_value_functions[&distribution](m_cached_samples[param_index][remainder].value);

        weight *= m_cached_samples[param_index][remainder].weight;
        if (param_index == 0)
            break;
    }
    return weight;
}

void DistributionHandler::defineCallbackForDistribution(const ParameterDistribution* distribution,
                                                        std::function<void(double)> fn)
{
    m_set_value_functions[distribution] = fn;
}
