//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/Detector/OffspecDetector.cpp
//! @brief     Implements class OffspecDetector.
//!
//! @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 "Device/Detector/OffspecDetector.h"
#include "Base/Axis/MakeScale.h"
#include "Base/Axis/Pixel.h"
#include "Base/Axis/Scale.h"
#include "Base/Util/Assert.h"
#include <iostream>

OffspecDetector::OffspecDetector(size_t n_phi, double phi_min, double phi_max, size_t n_alpha,
                                 double alpha_min, double alpha_max)
    : m_axes{std::make_shared<Scale>(EquiDivision("phi_f (rad)", n_phi, phi_min, phi_max)),
             std::make_shared<Scale>(EquiDivision("alpha_f (rad)", n_alpha, alpha_min, alpha_max))}
{
}

OffspecDetector::OffspecDetector(const OffspecDetector& other) = default;

OffspecDetector* OffspecDetector::clone() const
{
    return new OffspecDetector(*this);
}

void OffspecDetector::setAnalyzer(const R3& Bloch_vector, double mean_transmission)
{
    m_pol_analyzer = PolFilter(Bloch_vector, mean_transmission);
}

const Scale& OffspecDetector::axis(size_t index) const
{
    ASSERT(index < 2);
    return *m_axes[index];
}

size_t OffspecDetector::axisBinIndex(size_t i, size_t k_axis) const
{
    if (k_axis == 0)
        return i % m_axes[0]->size();
    else if (k_axis == 1)
        return i / m_axes[0]->size();
    ASSERT_NEVER;
}

size_t OffspecDetector::totalSize() const
{
    return m_axes[0]->size() * m_axes[1]->size();
}

Pixel* OffspecDetector::createPixel(size_t index) const
{
    const Scale& phi_axis = axis(0);
    const Scale& alpha_axis = axis(1);
    const size_t phi_index = axisBinIndex(index, 0);
    const size_t alpha_index = axisBinIndex(index, 1);

    const Bin1D alpha_bin = alpha_axis.bin(alpha_index);
    const Bin1D phi_bin = phi_axis.bin(phi_index);

    return new Pixel(phi_bin, alpha_bin);
}

size_t OffspecDetector::indexOfSpecular(double alpha, double phi) const
{
    const Scale& phi_axis = axis(0);
    const Scale& alpha_axis = axis(1);
    if (phi_axis.rangeComprises(phi) && alpha_axis.rangeComprises(alpha))
        return getGlobalIndex(phi_axis.closestIndex(phi), alpha_axis.closestIndex(alpha));
    return totalSize();
}

size_t OffspecDetector::getGlobalIndex(size_t x, size_t y) const
{
    return y * axis(0).size() + x;
}
