/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | www.openfoam.com
     \\/     M anipulation  |
-------------------------------------------------------------------------------
    Copyright (C) 2016 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM 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 General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "springDamperCOM.H"
#include "rigidBodyModel.H"
#include "addToRunTimeSelectionTable.H"

// #include "rigidBodyMotion.H"

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{
namespace RBD
{
namespace restraints
{
    defineTypeNameAndDebug(springDamperCOM, 0);

    addToRunTimeSelectionTable
    (
        restraint,
        springDamperCOM,
        dictionary
    );
}
}
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::RBD::restraints::springDamperCOM::springDamperCOM
(
    const word& name,
    const dictionary& dict,
    const rigidBodyModel& model
)
:
    restraint(name, dict, model)
{
    read(dict);
}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::RBD::restraints::springDamperCOM::~springDamperCOM()
{}


// * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * * //

void Foam::RBD::restraints::springDamperCOM::restrain
(
    scalarField& tau,
    Field<spatialVector>& fx,
    const rigidBodyModelState& state
) const
{
	label referenceID = model_.bodyID(reaction);				// reaction_ means a rigid body name  
	Tensor<scalar> Rr = model_.X0(referenceID).E().T(), Rb = model_.X0(bodyID_).E().T();
//	Tensor<scalar> rRb = Rr.T() & Rb;
	vector posvect = (model_.X0(bodyID_).inv() && spatialVector(Zero, target_position)).l() - (model_.X0(referenceID).inv() && spatialVector(Zero, reference_position)).l();
	vector velvect = model_.v(bodyID_, target_position).l() - model_.v(referenceID, reference_position).l();
    	vector unit_vector = posvect / (mag(posvect) + VSMALL);

    	// Force and moment on the master body including optional damping: 0.0 means target.
   	vector force( ( gain[0] * ( 0.0 - mag(posvect) ) + gain[1] * ( 0.0 - (unit_vector & velvect) ) ) * unit_vector );

	vector momentb( (Rb & target_position) ^ force );
	vector momentr( (Rr & reference_position) ^ force );

    if (model_.debug)
//    if ( RBD::rigidBodyMotion::Iteration_number_for_MB_ == 0 )
    {
	Info<< " springDamperCOM: " << endl
	<< model_.name(bodyID_) << " [" << bodyID_ << ", " << bodyIndex_<< "]" << endl
	<< Rb << endl << (model_.X0(bodyID_).inv() && spatialVector(Zero, target_position)).l() << endl;
	Info 
	<< reaction << " [" << referenceID << "]" << endl
	<< Rr << endl << (model_.X0(referenceID).inv() && spatialVector(Zero, reference_position)).l() << endl;
	Info
	<< " posvect: " << posvect << ", velvect: " << velvect << endl 
	<< " unit vector: " << unit_vector << " mag: " << mag(unit_vector) << endl 
	<< " P  " << ( gain[0] * ( 0.0 - mag(posvect) ) * unit_vector )
	<< " D  " << (-gain[1] * velvect )
	<< " foce(P+D) " << force << endl
	<< "momentb: " << momentb << ", momentr: -" << momentr << endl;
	if( ( referenceID == 0 ) || ( bodyID_ == 0 ) )	Info << "The force and moment are not reacted to the root" << endl;
    }

    	// Accumulate the force for the restrained body
    	if( bodyIndex_ != 0 )	fx[bodyIndex_]  += spatialVector( momentb, force );
    	if( referenceID != 0 )	fx[referenceID] -= spatialVector( momentr, force );
}

bool Foam::RBD::restraints::springDamperCOM::read
(
    const dictionary& dict
)
{
    restraint::read(dict);

    coeffs_.readEntry("target_position", target_position);
    coeffs_.readEntry("reference_position", reference_position);
    coeffs_.readEntry("gain", gain);
    coeffs_.readEntry("reaction", reaction);

    return true;
}


void Foam::RBD::restraints::springDamperCOM::write
(
    Ostream& os
) const
{
    restraint::write(os);

    os.writeEntry("target_position", target_position);
    os.writeEntry("reference_position", reference_position);
    os.writeEntry("gain", gain);
    os.writeEntry("reaction", reaction);
}


// ************************************************************************* //
