//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/Detector/SphericalDetector.cpp
//! @brief     Implements class SphericalDetector.
//!
//! @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 "Base/Const/PhysicalConstants.h"
#include "Base/Util/Assert.h"
#include "Device/Beam/Beam.h"
#include "Device/Resolution/IDetectorResolution.h"

using PhysConsts::pi;

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)))
{
    ASSERT(-pi / 2 < axis(0).min() && axis(0).max() < +pi / 2);
    ASSERT(-pi / 2 < axis(1).min() && axis(1).max() < +pi / 2);
}

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

Pixel* SphericalDetector::createPixel(size_t index) const
{
    const size_t ix = axisBinIndex(index, 0);
    const size_t iy = axisBinIndex(index, 1);

    const Bin1D& phi_in = axis(0).bin(ix);
    const Bin1D phi_out = Bin1D::FromTo(atan(phi_in.min()), atan(phi_in.max()));

    const double ru = hypot(1., pow(phi_in.center(), 2));
    const Bin1D& alpha_in = axis(1).bin(iy);
    const Bin1D alpha_out = Bin1D::FromTo(atan(alpha_in.min() / ru), atan(alpha_in.max() / ru));

    return new Pixel(phi_out, alpha_out);
}

size_t SphericalDetector::indexOfSpecular(const Beam& beam) const
{
    const double alpha = beam.alpha_i();
    const double phi = beam.phi_i();

    const double u = tan(phi);
    const double v = hypot(1., u * u) * tan(alpha);

    if (axis(0).rangeComprises(u) && axis(1).rangeComprises(v))
        return getGlobalIndex(axis(0).closestIndex(u), axis(1).closestIndex(v));
    return totalSize();
}
