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

using std::numbers::pi;

Detector2D::Detector2D(double phi_span, double alpha_span, size_t n_phi, size_t n_alpha,
                       double phi_center, double alpha_center)
    : IDetector(new Frame(
        newEquiDivision("phi_f (rad)", n_phi, phi_center - phi_span / 2, phi_center + phi_span / 2),
        newEquiDivision("alpha_f (rad)", n_alpha, alpha_center - alpha_span / 2,
                        alpha_center + alpha_span / 2)))
{
    ASSERT(-pi / 2 < axis(0).min() && axis(0).max() < +pi / 2);
    ASSERT(-pi / 2 < axis(1).min() && axis(1).max() < +pi / 2);
}

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

Pixel* Detector2D::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 Detector2D::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();
}
