//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/Detector/SphericalDetector.cpp
//! @brief     Implements class SphericalDetector. Obsolete, will be removed in v23.
//!
//! @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/SphericalDetector.h"
#include "Base/Axis/Frame.h"
#include "Base/Axis/MakeScale.h"
#include "Base/Axis/Pixel.h"
#include "Base/Axis/Scale.h"
#include "Device/Beam/Beam.h"
#include "Device/Resolution/IDetectorResolution.h"
#include <stdexcept>

SphericalDetector::SphericalDetector(size_t n_phi, double phi_min, double phi_max, size_t n_alpha,
                                     double alpha_min, double alpha_max)
    : IDetector(new Frame(newEquiDivision("phi_f (rad)", n_phi, phi_min, phi_max),
                          newEquiDivision("alpha_f (rad)", n_alpha, alpha_min, alpha_max)))
{
    throw std::runtime_error("In BornAgain 22, SphericalDetector has been replaced by Detector2D");
}

SphericalDetector::SphericalDetector(size_t n_bin, double width, double phi, double alpha)
    : SphericalDetector(n_bin, phi - width / 2, phi + width / 2, n_bin, alpha - width / 2,
                        alpha + width / 2)
{
}

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

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

Pixel* SphericalDetector::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 SphericalDetector::indexOfSpecular(const Beam& beam) const
{
    double alpha = beam.alpha_i();
    double phi = beam.phi_i();
    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();
}
