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

// #include "rigidBodyMotion.H"

#define	deg(a)	((a)*180.0/3.141592)	// from rad to deg

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

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

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


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

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


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

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


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

void Foam::RBD::restraints::coilSpringDamperCOM::restrain
(
    scalarField& tau,
    Field<spatialVector>& fx,
    const rigidBodyModelState& state
) const
{
	label referenceID = model_.bodyID(reaction);				// reaction_ means a rigid body name  
	vector moment = Zero, axis = Zero;
	Tensor<scalar> Rr = model_.X0(referenceID).E().T(), Rb = model_.X0(bodyID_).E().T();
	Tensor<scalar> rRb = Rr.T() & Rb;
	vector angular_vel = Rr.T() & ( model_.v(bodyID_).w() - model_.v(referenceID).w() );

	/*** Rodrigues rotation ***/
	double theta = atan2( sqrt( pow(rRb.yx()-rRb.xy(),2.0) + pow(rRb.xz()-rRb.zx(),2.0) + pow(rRb.zy()-rRb.yz(),2.0) ), rRb.xx() + rRb.yy()+ rRb.zz() - 1 );

	if( 1.0e-32 < mag(sin(theta)) ){
	    axis[2] = rRb.yx() - rRb.xy(); 
	    axis[1] = rRb.xz() - rRb.zx(); 
	    axis[0] = rRb.zy() - rRb.yz();
	    axis /= (2.0*sin(theta));
	    moment =-gain[0] * theta * axis; 
	}

	moment -= ( gain[1] * angular_vel );
//	moment -= ( gain[1] * ( angular_vel & axis ) * axis );


    if ( model_.debug )
//    if ( RBD::rigidBodyMotion::Iteration_number_for_MB_ == 0 )
    {
	Info<< " coilSpringDamperCOM: " << endl
	<< model_.name(bodyID_) << "[" << bodyID_ << ", " << bodyIndex_ << "], " << reaction << "[" << referenceID << "]" << endl;
//	<< " Rr  " << Rr << endl
//	<< " Rb  " << Rb << endl
//	<< " rRb " << rRb << endl
//	<< " gain " << gain_;
	Info << " theta " << deg(theta) << ", n: " << axis 
	     << " vel " << (angular_vel*180.0/3.141592) << endl
		<< " P  " << (-gain[0] * theta * axis)
		<< " D  " << (-gain[1] * ( angular_vel & axis ) * axis ) 
		<< " moment(P+D): " << moment << endl;
	if( ( referenceID == 0 ) || ( bodyID_ == 0 ) )	Info << "The moment is not reacted to the root" << endl;
    }

    	// Accumulate the force for the restrained body
    if( bodyIndex_ != 0 )	fx[bodyIndex_]  += spatialVector( Rr & moment, Zero /*force*/ );
    if( referenceID != 0 )	fx[referenceID] -= spatialVector( Rr & moment, Zero /*force*/ );
}

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

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

    return true;
}


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

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


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