/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  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 "angleControlWaveCOM.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(angleControlWaveCOM, 0);

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


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

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


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

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


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

void Foam::RBD::restraints::angleControlWaveCOM::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();
    	const double amp = parameters_.yx(), freq = parameters_.yy(), phase = parameters_.yz(), shift = parameters_.zx();
	const double axis = parameters_.zy(), relaxation_time = parameters_.zz(), 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() );
	double target_angle = amp * sin( 2.0*3.141592 * freq * t + phase ) + shift;
	double target_anglularvel = 2.0*3.141592 * freq * amp * cos( 2.0*3.141592 * freq * t + phase );

	if( t < relaxation_time  ){
		target_angle *= (t/relaxation_time);
		target_anglularvel *= (t/relaxation_time);
	}

	if( axis < 0.5 )	moment[0] = Pgain * ( target_angle - atan2( rRb.zy(), rRb.yy() ) ) + Dgain * ( target_anglularvel - angular_vel[0] ); /* x */
	else if( axis < 1.5 )	moment[1] = Pgain * ( target_angle - atan2(-rRb.zx(), rRb.xx() ) ) + Dgain * ( target_anglularvel - angular_vel[1] ); /* y */
	else			moment[2] = Pgain * ( target_angle - atan2( rRb.yx(), rRb.xx() ) ) + Dgain * ( target_anglularvel - 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<< " angleControlWaveCOM: " << endl
	<< model_.name(bodyID_) << "["<< bodyID_ << ", " << bodyIndex_ << "], " << reaction_ << "[" <<referenceID << "]" << endl
	<< " amp[deg] = " << deg(amp) << ", freq = " << freq << ", phase[deg] = " << deg(phase) << ", shift[deg] = " << deg(shift) << endl
	<< " axis = " << axis << ", t= " << t << 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 " << deg(target_anglularvel) << ", " << deg(angular_vel[0]) << endl
		<< " P  " << (Pgain * ( target_angle - atan2( rRb.zy(), rRb.yy() ) ))
		<< " D  " << (Dgain * ( target_anglularvel - 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 " << deg( target_anglularvel) << ", " << deg(angular_vel[1]) << endl
		<< " P  " << (Pgain * ( target_angle - atan2(-rRb.zx(), rRb.xx()) ))
		<< " D  " << (Dgain * ( target_anglularvel - 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 " << deg( target_anglularvel) << ", " << deg(angular_vel[2]) << endl
		<< " P  " << (Pgain * ( target_angle - atan2( rRb.yx(), rRb.xx() ) ) )
		<< " D  " << (Dgain * ( target_anglularvel - 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::angleControlWaveCOM::read
(
    const dictionary& dict
)
{
    restraint::read(dict);

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

    return true;
}


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

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


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