/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#ifndef LINEARSUBSPACE_LSMultiMapping_H
#define LINEARSUBSPACE_LSMultiMapping_H

#include <sofa/core/Multi2Mapping.h>
#include <SofaEigen2Solver/EigenSparseMatrix.h>

#include <Flexible/deformationMapping/LinearJacobianBlock.h>
#include "LSJacobianBlock.h"
#include "../shapeFunction/BaseLSShapeFunction.h"


namespace sofa
{
namespace component
{
namespace mapping
{

template <class TIn1, class TIn2, class TOut>
class LSMultiMapping : public core::Multi2Mapping<TIn1, TIn2, TOut>
{
public:
    typedef core::Multi2Mapping<TIn1, TIn2, TOut> Inherit;
    SOFA_CLASS(SOFA_TEMPLATE3(LSMultiMapping,TIn1,TIn2,TOut), SOFA_TEMPLATE3(core::Multi2Mapping,TIn1,TIn2,TOut));

    /// Input Model Type
    typedef TIn1 In1;
    typedef TIn2 In2;
    /// Output Model Type
    typedef TOut Out;

    /** @name  Input types    */
    //@{
    typedef typename In1::Real Real;
    typedef typename In1::VecCoord In1VecCoord;
    typedef Data<In1VecCoord> In1DataVecCoord;
    typedef typename In1::VecDeriv In1VecDeriv;
    typedef Data<In1VecDeriv> In1DataVecDeriv;

    typedef typename In2::VecCoord In2VecCoord;
    typedef Data<In2VecCoord> In2DataVecCoord;
    typedef typename In2::VecDeriv In2VecDeriv;
    typedef Data<In2VecDeriv> In2DataVecDeriv;

    typedef typename In2::SpatialCoord In2Pos;
    typedef typename In2::Frame In2Frame;
    //@}

    /** @name  Output types    */
    //@{
    typedef typename Out::Coord OutCoord;
    typedef typename Out::VecCoord OutVecCoord;
    typedef Data<OutVecCoord> OutDataVecCoord;
    typedef typename Out::Deriv OutDeriv;
    typedef typename Out::VecDeriv OutVecDeriv;
    typedef Data<OutVecDeriv> OutDataVecDeriv;
    enum { spatial_dimensions = Out::spatial_dimensions };
    //@}

    /** @name  Shape Function types    */
    //@{
    typedef core::behavior::LSShapeFunctionTypes< spatial_dimensions, Real> ShapeFunctionType;
    typedef core::behavior::BaseLSShapeFunction<ShapeFunctionType> BaseLSShapeFunction;
    typedef typename BaseLSShapeFunction::Weight Weight;
    typedef typename BaseLSShapeFunction::VWeight VWeight;
    typedef typename BaseLSShapeFunction::VecVWeight VecVWeight;
    typedef typename BaseLSShapeFunction::AffineWeight AffineWeight;
    typedef typename BaseLSShapeFunction::VAffineWeight VAffineWeight;
    typedef typename BaseLSShapeFunction::VecVAffineWeight VecVAffineWeight;
    typedef typename BaseLSShapeFunction::VRef VRef;
    typedef typename BaseLSShapeFunction::VecVRef VecVRef;
    // @}

    /** @name  Jacobian types    */
    //@{
    typedef typename defaulttype::LSJacobianBlock<In1,Out> BlockType1;
    typedef helper::vector<helper::vector<BlockType1> >  SparseMatrix1;
    typedef typename defaulttype::LSJacobianBlock<In2,Out> BlockType2;
    typedef helper::vector<helper::vector<BlockType2> >  SparseMatrix2;

    typedef typename BlockType1::MatBlock  MatBlock1;  ///< Jacobian block matrix
    typedef linearsolver::EigenSparseMatrix<In1,Out>    SparseMatrixEigen1;
    typedef typename BlockType2::MatBlock  MatBlock2;  ///< Jacobian block matrix
    typedef linearsolver::EigenSparseMatrix<In2,Out>    SparseMatrixEigen2;

    typedef typename BlockType1::KBlock  KBlock1;  ///< stiffness block matrix
    typedef linearsolver::EigenSparseMatrix<In1,In1>    SparseKMatrixEigen1;
    typedef typename BlockType2::KBlock  KBlock2;  ///< stiffness block matrix
    typedef linearsolver::EigenSparseMatrix<In2,In2>    SparseKMatrixEigen2;
    //@}

    /** @name Mapping functions */
    //@{
    virtual void init();
    virtual void reinit();


    void apply(const core::MechanicalParams * mparams , Data<OutVecCoord>& dOut, const Data<In1VecCoord>& dIn1, const Data<In2VecCoord>& dIn2);
    // trivial implementation, consistant with what is done in flexible
    virtual void apply(
        const core::MechanicalParams* mparams,
        const helper::vector<Data<OutVecCoord>*>& dOut,
        const helper::vector<const Data<In1VecCoord>*>& dIn1,
        const helper::vector<const Data<In2VecCoord>*>& dIn2)
    {
        apply(mparams,*dOut[0],*dIn1[0],*dIn2[0]);
    }
    void applyJ(const core::MechanicalParams * /*mparams*/ , Data<OutVecDeriv>& dOut, const Data<In1VecDeriv>& dIn1, const Data<In2VecDeriv>& dIn2);
    virtual void applyJ(const core::MechanicalParams* mparams , const helper::vector<Data<OutVecDeriv>*>& dOut, const helper::vector<const Data<In1VecDeriv>*>& dIn1, const helper::vector<const Data<In2VecDeriv>*>& dIn2)
    {
        if(this->isMechanical())
            applyJ(mparams,*dOut[0],*dIn1[0],*dIn2[0]);
    }

//    virtual void apply(
//        const core::MechanicalParams* mparams,
//        const helper::vector<OutDataVecCoord*>& dOut,
//        const helper::vector<const In1DataVecCoord*>& dIn1 ,
//        const helper::vector<const In2DataVecCoord*>& dIn2);

    void applyJT(const core::MechanicalParams * /*mparams*/ , Data<In1VecDeriv>& dIn1, Data<In2VecDeriv>& dIn2, const Data<OutVecDeriv>& dOut);
    virtual void applyJT(
        const core::MechanicalParams* mparams, const helper::vector< In1DataVecDeriv*>& dIn1,
        const helper::vector< In2DataVecDeriv*>& dIn2,
        const helper::vector<const OutDataVecDeriv*>& dOut)
    {
        if(this->isMechanical())
            applyJT(mparams,*dIn1[0],*dIn2[0],*dOut[0]);
    }



    virtual void applyDJT(const core::MechanicalParams* mparams, core::MultiVecDerivId parentDfId, core::ConstMultiVecDerivId );

    virtual const helper::vector<sofa::defaulttype::BaseMatrix*>* getJs();

    //@}

    void draw(const core::visual::VisualParams* vparams);

    virtual size_t getFromSize1() const { return this->fromModels1[0]->getSize(); }
    virtual size_t getFromSize2() const { return this->fromModels2[0]->getSize(); }
    virtual size_t getToSize()  const { return this->toModel->getSize(); }

    Data<std::string> d_shapeFunctionName; ///< name of the shape function component (optional: if not specified, will searchup)
    Data<VecVRef > d_index1;            ///< The numChildren * numRefs column indices. index1[i][j] is the index of the j-th parent of type 1 influencing child i.
    Data<VecVRef > d_index2;            ///< The numChildren * numRefs column indices. index2[i][j] is the index of the j-th parent of type 2 influencing child i.
    Data<VecVWeight > d_weight1;        ///< The numChildren * numRefs weights. weight1[i][j] is the weight of the j-th parent of type 1
    Data<VecVAffineWeight > d_weight2;  ///< The numChildren * numRefs weights. weight2[i][j] is the weight of the j-th parent of type 2

    Data<bool> d_assemble;

protected:
    LSMultiMapping();
    virtual ~LSMultiMapping() { }

    BaseLSShapeFunction* m_shapeFunction;        ///< where the weights are computed

    SparseMatrix1 jacobian1;   ///< Jacobian of the mapping
    SparseMatrix2 jacobian2;   ///< Jacobian of the mapping
    virtual void initJacobianBlocks();

    SparseMatrixEigen1 eigenJacobian1;  ///< Assembled Jacobian matrix
    void updateJ1();
    SparseMatrixEigen2 eigenJacobian2;  ///< Assembled Jacobian matrix
    void updateJ2();
    helper::vector<defaulttype::BaseMatrix*> baseMatrices;      ///< Vector of jacobian matrices, for the Compliant plugin API

    core::State<In1>* fromModel1;   ///< DOF of the master1
    core::State<In2>* fromModel2;   ///< DOF of the master2
    core::State<Out>* toModel;      ///< DOF of the slave

};


}
}
}

#endif
