//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Lattice/Lattice3D.h
//! @brief     Defines class Lattice.
//!
//! @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)
//
//  ************************************************************************************************

#ifndef BORNAGAIN_SAMPLE_LATTICE_LATTICE3D_H
#define BORNAGAIN_SAMPLE_LATTICE_LATTICE3D_H

#include "Base/Vector/RotMatrix.h"
#include "Param/Node/INode.h"
#include <heinz/Vectors3D.h>
#include <memory>
#include <vector>

class ISelectionRule;

//! A Bravais lattice, characterized by three basis vectors, and optionally an ISelectionRule.

class Lattice3D : public INode {
public:
    Lattice3D(const R3& a, const R3& b, const R3& c);
    Lattice3D(const Lattice3D& lattice);
    ~Lattice3D() override;
    Lattice3D& operator=(const Lattice3D&) = delete;

    std::string className() const final { return "Lattice3D"; }

    //! Creates rotated lattice
    Lattice3D rotated(const RotMatrix& rotMatrix) const;

    //! Returns basis vector a
    R3 basisVectorA() const { return m_a; }

    //! Returns basis vector b
    R3 basisVectorB() const { return m_b; }

    //! Returns basis vector c
    R3 basisVectorC() const { return m_c; }

    //! Returns normalized direction corresponding to the given Miller indices
    R3 getMillerDirection(double h, double k, double l) const;

    //! Returns the volume of the unit cell
    double unitCellVolume() const;

    //! Returns the reciprocal basis vectors
    void reciprocalLatticeBasis(R3& ra, R3& rb, R3& rc) const;

    //! Sets a selection rule for the reciprocal vectors
    void setSelectionRule(const ISelectionRule& selection_rule);

#ifndef SWIG
    //! Returns the selection rule for the reciprocal vectors
    const ISelectionRule* selectionRule() const { return m_selection_rule.get(); }

    //! Returns a list of reciprocal lattice vectors within distance dq of a vector q
    std::vector<R3> reciprocalLatticeVectorsWithinRadius(const R3& q, double dq) const;

    //... private but for test:

    //! Returns the nearest reciprocal lattice point from a given vector
    I3 nearestI3(const R3& q) const;

private:
    void computeReciprocalVectors() const;

    R3 m_a, m_b, m_c; //!< Basis vectors in real space
    std::unique_ptr<ISelectionRule> m_selection_rule;

    mutable R3 m_ra, m_rb, m_rc; //!< Cache of basis vectors in reciprocal space
#endif                           // SWIG
};

//! Comparison operator for lattices (equality check)
bool operator==(const Lattice3D& left, const Lattice3D& right);

#endif // BORNAGAIN_SAMPLE_LATTICE_LATTICE3D_H
