/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | www.openfoam.com
     \\/     M anipulation  |
-------------------------------------------------------------------------------
    Copyright (C) 2019 OpenFOAM Foundation
    Copyright (C) 2020 OpenCFD Ltd.
-------------------------------------------------------------------------------
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 "angleControlCOM.H"
#include "rigidBodyModel.H"
#include "rigidBodyModelState.H"
#include "OneConstant.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(angleControlCOM, 0);

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


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

Foam::RBD::restraints::angleControlCOM::angleControlCOM
(
    const word& name,
    const dictionary& dict,
    const rigidBodyModel& model
)
:
    restraint(name, dict, model),
    parameters_(Tensor<scalar>::zero)
{
    read(dict);
}


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

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


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

void Foam::RBD::restraints::angleControlCOM::restrain
(
    scalarField& tau,
    Field<spatialVector>& fx,
    const rigidBodyModelState& state
) const
{
	label referenceID = model_.bodyID(reaction_);				// reaction_ means a rigid body name  
    	const double Pgain = parameters_.xx(), Dgain = parameters_.xy(), Maxgain = parameters_.xz();
	double target_angle = parameters_.yx();
    	const double axis = parameters_.yy(), relaxation_time = parameters_.yz();
	const double t = state.t();
	vector moment = 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() );

	if( t < relaxation_time  )	target_angle *= (t/relaxation_time);

	if( axis < 0.5 )	moment[0] = Pgain * ( target_angle - atan2( rRb.zy(), rRb.yy() ) ) + Dgain * ( 0.0 - angular_vel[0] ); /* x */
	else if( axis < 1.5 )	moment[1] = Pgain * ( target_angle - atan2(-rRb.zx(), rRb.xx() ) ) + Dgain * ( 0.0 - angular_vel[1] ); /* y */
	else			moment[2] = Pgain * ( target_angle - atan2( rRb.yx(), rRb.xx() ) ) + Dgain * ( 0.0 - angular_vel[2] ); /* z */
	
	double	torque = mag( moment );	
	if( Maxgain < torque )	moment *= ( Maxgain / torque );

    if( model_.debug )
//    if ( RBD::rigidBodyMotion::Iteration_number_for_MB_ == 0 )
    {
	Info<< " angleControlCOM: " << endl
	<< model_.name(bodyID_) << "["<< bodyID_ << ", " << bodyIndex_ << "], " << reaction_ << "[" << referenceID << "]" << endl
	<< " target angle [deg] = " << deg(target_angle) << endl << " axis = " << axis << endl;
//	<< " Rr  " << Rr << endl
//	<< " Rb  " << Rb << endl
//	<< " rRb " << rRb << endl
	if( axis < 0.5 )
	   Info << " X:target angle " << deg(target_angle) << ", " << deg(atan2( rRb.zy(), rRb.yy() )) << endl
	     	<< " target vel " << " 0.0, " << deg(angular_vel[0]) << endl
		<< " P  " << (Pgain * ( target_angle - atan2( rRb.zy(), rRb.yy() ) ))
		<< " D  " << (Dgain * ( 0.0 - angular_vel[0] ) )
		<< " moment(P+D) " << moment << endl;
	else if( axis < 1.5 )
	   Info << " Y:target angle " << deg(target_angle) << ", " << deg(atan2(-rRb.zx(), rRb.xx())) << endl
	     	<< " target vel " << " 0.0, " << deg(angular_vel[1]) << endl
		<< " P  " << (Pgain * ( target_angle - atan2(-rRb.zx(), rRb.xx()) ))
		<< " D  " << (Dgain * ( 0.0 - angular_vel[1] ) )
		<< " moment(P+D) " << moment << endl;
	else
	   Info << " Z:target angle " << deg(target_angle) << ", " << deg(atan2( rRb.yx(), rRb.xx())) << endl
	     	<< " target vel " << " 0.0, " << deg(angular_vel[2]) << endl
		<< " P  " << (Pgain * ( target_angle - atan2( rRb.yx(), rRb.xx() ) ) )
		<< " D  " << (Dgain * ( 0.0 - angular_vel[2] ) )
		<< " moment(P+D) " << moment << endl;
	if( ( referenceID == 0 ) || ( bodyID_ == 0 ) )	Info << "The moment is not reacted to the root" << endl;
    }

    // Accumulate the ONLY MOMENT 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::angleControlCOM::read
(
    const dictionary& dict
)
{
    restraint::read(dict);

    coeffs_.readEntry("parameters", parameters_);
    coeffs_.readEntry("reaction", reaction_);

    return true;
}


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

    os.writeEntry("parameters", parameters_);
    os.writeEntry("reaction", reaction_);
}


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