/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  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 "collisionCOM.H"
#include "rigidBodyModel.H"
#include "addToRunTimeSelectionTable.H"

//#include "rigidBodyMotion.H"

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

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

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


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

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


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

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


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

void Foam::RBD::restraints::collisionCOM::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	target_vector = target_point - model_.I(bodyID_).c();
	vector	reference_vector = reaction_point - model_.I(referenceID).c();

	vector posvect = (model_.X0(bodyID_).inv() && spatialVector(Zero, target_vector)).l() - (model_.X0(referenceID).inv() && spatialVector(Zero, reference_vector)).l();
	vector velvect = model_.v(bodyID_, target_vector).l() - model_.v(referenceID, reference_vector).l();
    	vector unit_vector = posvect / (mag(posvect) + VSMALL);

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

	  vector momentb( (Rb & target_vector) ^ force );
	  vector momentr( (Rr & reference_vector) ^ force );

    if ( model_.debug )
//    if ( RBD::rigidBodyMotion::Iteration_number_for_MB_ == 0 )
    {
	Info<< " collisionCOM: " << endl
	<< model_.name(bodyID_) << " [" << bodyID_ << ", " << bodyIndex_ << "]" << endl
	<< Rb << endl << (model_.X0(bodyID_).inv() && spatialVector(Zero, target_vector)).l() << endl;
	Info 
	<< reaction << " [" << referenceID << "]" << endl
	<< Rr << endl << (model_.X0(referenceID).inv() && spatialVector(Zero, reference_vector)).l() << endl;
	Info
	<< " posvect: " << posvect << ", velvect: " << velvect << endl 
	<< " unit vector: " << unit_vector << " mag: " << mag(unit_vector) << endl 
	<< " P  " << ( gain[0] * ( gain[2] - 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::collisionCOM::read
(
    const dictionary& dict
)
{
    restraint::read(dict);

    coeffs_.readEntry("target_point", target_point);
    coeffs_.readEntry("reaction_point", reaction_point);
    coeffs_.readEntry("gain", gain);
    coeffs_.readEntry("reaction", reaction);

    return true;
}


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

    os.writeEntry("target_point", target_point);
    os.writeEntry("reaction_point", reaction_point);
    os.writeEntry("gain", gain);
    os.writeEntry("reaction", reaction);
}


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