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

#include "rigidBodyMotion.H"

#define	deg(a)	((a)*180.0/3.141592)

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

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

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


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

Foam::RBD::restraints::torqueControl::torqueControl
(
    const word& name,
    const dictionary& dict,
    const rigidBodyModel& model
)
:
    restraint(name, dict, model),
    target_(nullptr),
    gain_(Zero)
{
    read(dict);
}


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

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


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

void Foam::RBD::restraints::torqueControl::restrain
(
    scalarField& tau,
    Field<spatialVector>& fx,
    const rigidBodyModelState& state
) const
{
	label referenceID = model_.bodyID(reaction_);				// reaction_ means a rigid body name  
    	const vector target = target_().value(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() );	/* in the tail coordinate system */
	
	moment[2] = gain_[0] * ( target[0] - atan2( rRb.yx(), rRb.xx() ) ) + gain_[1] * ( target[1] - angular_vel[2] );
	if( gain_[2] < moment[2] )		moment[2] = gain_[2];
	else if( moment[2] < -gain_[2] )	moment[2] =-gain_[2];

    if( RBD::rigidBodyMotion::Iteration_number_for_MB_ == 0 )
    {
	Info<< " torque control: " << endl
	<< " ID:  " << bodyID_ << ", " << reaction_ << referenceID << endl
	<< " gain " << gain_
	<< " target angle " << deg(target[0]) << ", " << deg(atan2( rRb.yx(), rRb.xx() )) << endl
	<< " target vel "   << deg(target[1]) << ", " << deg(angular_vel[2]) << endl
//	<< " Rr  " << Rr << endl
//	<< " Rb  " << Rb << endl
//	<< " rRb " << rRb << endl

	<< " P  " << (gain_[0] * ( target[0] - atan2( rRb.yx(), rRb.xx() ) ))
	<< " D  " << (gain_[1] * ( target[1] - angular_vel[2] ) )
	
	<< " moment(P+D) " << moment[2] << endl;
    }

    // Accumulate the ONLY MOMENT for the restrained body


//Info << "body fx" << fx[bodyIndex_] << endl;
//Info << "reference fx" << fx[referenceID] << endl;



    fx[bodyIndex_]  += spatialVector( Rr & moment, Zero /*force*/ );
    fx[referenceID] -= spatialVector( Rr & moment, Zero /*force*/ );
}


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

    coeffs_.readEntry("gain", gain_);

    target_ = Function1<vector>::New("target", coeffs_);

    coeffs_.readEntry("reaction", reaction_);

    return true;
}


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

    os.writeEntry("gain", gain_);
    os.writeEntry("reaction", reaction_);

    target_().writeData(os);
}


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