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

//#include "rigidBodyMotion.H"

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

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

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

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


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

Foam::RBD::restraints::fishlocomotionCOM::fishlocomotionCOM
(
    const word& name,
    const dictionary& dict,
    const rigidBodyModel& model
)
:
    restraint(name, dict, model),
    fishlocomotionCOMReport_( dict.getOrDefault<bool>("report", false))
{
    read(dict);
}


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

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


// * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * * //
void Foam::RBD::restraints::fishlocomotionCOM::RodriguesMatrixFromVector
(
    Tensor<scalar>& R,
    const vector rod
) const
{
    scalar theta = mag(rod);
    vector n(rod/(theta + VSMALL));

    R.xx() = cos(theta) + n[0]*n[0] * ( 1.0 - cos(theta) );		R.xy() = n[0]*n[1] * ( 1.0 - cos(theta) ) - n[2] * sin(theta);	R.xz() = n[2]*n[0] * ( 1.0 - cos(theta) ) + n[1] * sin(theta);
    R.yx() = n[0]*n[1] * ( 1.0 - cos(theta) ) + n[2] * sin(theta);	R.yy() = cos(theta) + n[1]*n[1] * ( 1.0 - cos(theta) );		R.yz() = n[1]*n[2] * ( 1.0 - cos(theta) ) - n[0] * sin(theta);
    R.zx() = n[2]*n[0] * ( 1.0 - cos(theta) ) - n[1] * sin(theta);	R.zy() = n[1]*n[2] * ( 1.0 - cos(theta) ) + n[0] * sin(theta);	R.zz() = cos(theta) + n[2]*n[2] * ( 1.0 - cos(theta) );
}

Foam::vector Foam::RBD::restraints::fishlocomotionCOM::RodriguesVectorFromMatrix
(
    const Tensor<scalar> R
) const
{
    vector	n(0,0,0);
    scalar	xx, yy, theta;
    yy = sqrt( sqr(R.xy()-R.yx()) + sqr(R.xz()-R.zx()) + sqr(R.yz()-R.zy()) ) / 2.0;
    xx = ( R.xx() + R.yy() + R.zz() - 1 ) / 2.0;

    theta = Foam::atan2( yy, xx );

    if( mag(theta) < (100*VSMALL) ){	// theta = 0 deg.
	n = Zero;
    }else if( mag( mag(theta) - mag(Foam::atan2(0.0,-1.0)) ) < (100*VSMALL) ){	// theta = +-180 deg.
	if( (R.xx()+1) < 0.0 ) 	n[0] = 0.0;
	else			n[0] = sqrt( (R.xx() + 1)/2.0 );
	if( (R.yy()+1) < 0.0 )  n[1] = 0.0;
	else{
	  if( R.yx() > 0 )	n[1] = sqrt( (R.yy() + 1)/2.0 );
	  else			n[1] =-sqrt( (R.yy() + 1)/2.0 );
	}
	if( (R.zz()+1) < 0.0 )	n[2] = 0.0;
	else{
	  if( R.zx() > 0 )	n[2] = sqrt( (R.zz() + 1)/2.0 );
	  else			n[2] =-sqrt( (R.zz() + 1)/2.0 );
	}
	n *= theta;

// Info << " theta*n " << n << endl;


    }else{
	n[0] = -(R.yz()-R.zy()) / (2.0*sin(theta));
	n[1] =  (R.xz()-R.zx()) / (2.0*sin(theta));
	n[2] = -(R.xy()-R.yx()) / (2.0*sin(theta));
	n *= theta;
    }

    return	n;
}

void Foam::RBD::restraints::fishlocomotionCOM::restrain
(
    scalarField& tau,
    Field<spatialVector>& fx,
    const rigidBodyModelState& state
) const
{
//	Info << "fishlocomotionCOM: " << endl;

	label referenceID = model_.bodyID(reaction_);		// reaction_ means a rigid body name  
	const double A0 = carangiform_[0], A1 = carangiform_[1];
	const double p0 = rolling_[0], p1 = rolling_[1], phase = rolling_[2];
	const double t = state.t(), dt = state.deltaT();
	Tensor<scalar> Rpitch;
	Rpitch.xx() = cos(initialPitch_);	Rpitch.xy() = 0.0;	Rpitch.xz() = sin(initialPitch_);
	Rpitch.yx() = 0.0;			Rpitch.yy() = 1.0;	Rpitch.yz() = 0.0;
	Rpitch.zx() =-sin(initialPitch_);	Rpitch.zy() = 0.0;	Rpitch.zz() = cos(initialPitch_);
	const double x = (Rpitch.T() & model_.I(bodyID_).c()).x() - x_origin_, rx = (Rpitch.T() & model_.I(referenceID).c()).x() - x_origin_;
	const double L = bodyLength_;

/*
Info << "body id = " << bodyID_<< endl;
Info << "model_.I(bodyID_).c() = " << model_.I(bodyID_).c() << endl;
Info << "(Rpitch.T() & model_.I(bodyID_).c()) = " << (Rpitch.T() & model_.I(bodyID_).c()) << endl;
Info << "x = " << x << endl;
*/


	// z: carangiform locomotion
	double 	dydx = ( A0 / L + 2.0 * A1 / L / L * x ) *  sin( 2.0*PI*( x/lambda_ - freq_*t ) )
		     + ( A0 / L * x + A1 / L / L * x * x ) * 2.0*PI/lambda_ * cos( 2.0*PI*( x/lambda_ - freq_*t ) );
	double rdydx = ( A0 / L + 2.0 * A1 / L / L * rx ) * sin( 2.0*PI*( rx/lambda_ - freq_*t ) )
		     + ( A0 / L *rx + A1 / L / L *rx *rx ) * 2.0*PI/lambda_ * cos( 2.0*PI*( rx/lambda_ - freq_*t ) );
	double zangle = atan( dydx ) -  atan( rdydx );

		dydx = ( A0 / L + 2.0 * A1 / L / L * x ) *  sin( 2.0*PI*( x/lambda_ - freq_*(t-dt) ) )
		     + ( A0 / L * x + A1 / L / L * x * x ) * 2.0*PI/lambda_ * cos( 2.0*PI*( x/lambda_ - freq_*(t-dt) ) );
	       rdydx = ( A0 / L + 2.0 * A1 / L / L * rx ) * sin( 2.0*PI*( rx/lambda_ - freq_*(t-dt) ) )
		     + ( A0 / L *rx + A1 / L / L *rx *rx ) * 2.0*PI/lambda_ * cos( 2.0*PI*( rx/lambda_ - freq_*(t-dt) ) );
	double preZangle = atan( dydx ) -  atan( rdydx );

	// x: body rolling
	double xangle = ( p0 / L * x + p1 / L / L * x * x ) * sin( 2.0*PI*( x/lambda_ - freq_*t ) + phase )
		      - ( p0 / L *rx + p1 / L / L *rx *rx ) * sin( 2.0*PI*(rx/lambda_ - freq_*t ) + phase );
	double preXangle = ( p0 / L * x + p1 / L / L * x * x ) * sin( 2.0*PI*( x/lambda_ - freq_*(t-dt) ) + phase )
			 - ( p0 / L *rx + p1 / L / L *rx *rx ) * sin( 2.0*PI*(rx/lambda_ - freq_*(t-dt) ) + phase );

	if( t < relaxationTime_  ){
		xangle *= (t/relaxationTime_);
		zangle *= (t/relaxationTime_);
		preXangle *= (t/relaxationTime_);
		preZangle *= (t/relaxationTime_);
	}

	Tensor<scalar> Rz, Rx, Rtarget, Rpre;
	vector	rod, zAxis(0, 0, 1), xAxis(1, 0, 0);

 	rod = zangle * ( Rpitch & zAxis );
	RodriguesMatrixFromVector( Rz, rod );
	rod = Rz & xAxis;
	rod = ( xangle / mag(rod) ) * rod;
	RodriguesMatrixFromVector( Rx, rod );
	Rtarget = Rx & Rz;			// warning:: correct ?

 	rod = preZangle * ( Rpitch & zAxis );
	RodriguesMatrixFromVector( Rz, rod );
	rod = Rz & xAxis;
	rod = ( preXangle / mag(rod) ) * rod;
	RodriguesMatrixFromVector( Rx, rod );
	Rpre = Rx & Rz;				// warning:: correct ?

	/*** relative body angle ***/
	const Tensor<scalar> Rr = model_.X0(referenceID).E().T(), Rb = model_.X0(bodyID_).E().T();
	const Tensor<scalar> rRb = Rr.T() & Rb;

	const Tensor<scalar> bRtarget = rRb.T() & Rtarget; // angle error
	vector RodVector = RodriguesVectorFromMatrix( bRtarget );
	RodVector = rRb & RodVector;

	/*** relative body anglular velocity ***/
	const vector angular_vel = Rr.T() & ( model_.v(bodyID_).w() - model_.v(referenceID).w() );

	const Tensor<scalar> preRtarget = Rpre.T() & Rtarget; 
	vector RodVVector = RodriguesVectorFromMatrix( preRtarget ) / dt;
	RodVVector = ( ( Rr.T() & Rpre ) & RodVVector ) - angular_vel;


	scalar	maxInertia = 0.0;
    	for(int i=0; i<((model_.nBodies()-1)/2); i++){
		maxInertia = max( maxInertia, (Rpitch.T() & model_.I(i).Ic()).zz() );
	}
	scalar weight = (Rpitch.T() & model_.I(bodyID_).Ic()).zz() / maxInertia;

	vector moment = weight * ( gain_[0] * RodVector + gain_[1] * RodVVector );

//	if( t < relaxationTime_  )	moment *= (t/relaxationTime_);

	if( gain_[2] < mag( moment ) )	moment *= ( gain_[2] / mag( moment ) );


    if (model_.debug || fishlocomotionCOMReport_)
//    if ( RBD::rigidBodyMotion::Iteration_number_for_MB_ == 0 )
    {
	Info<< " fishlocomotionCOM: " << endl
	<< model_.name(bodyID_) << "["<< bodyID_ << ", " << bodyIndex_ << "], " << reaction_ << "[" <<referenceID << "]" << endl
	<< "Initial Pitch angle [deg] = " << deg(initialPitch_) << endl
	<< "target z angle [deg] = " << deg(zangle) << " x angle [deg] = " << deg(xangle) << " ang.vel. [rad/s] = " <<  (RodriguesVectorFromMatrix( preRtarget ) / dt) << " , t= " << t << endl;
/*
Info << "R" << endl;
Info << Rtarget.xx() << " " << Rtarget.yx() << " " << Rtarget.zx() << endl;
Info << Rtarget.xy() << " " << Rtarget.yy() << " " << Rtarget.zy() << endl;
Info << Rtarget.xz() << " " << Rtarget.yz() << " " << Rtarget.zz() << endl;
Info << "Inertia body " << endl << model_.I(bodyID_).Ic().zz() << endl;
Info << "Inertia ref. " << endl << model_.I(referenceID).Ic().zz() << endl; */
Info << "Inertia weight " << weight << " " << maxInertia << " " << ((model_.nBodies()-1)/2) << endl;

	Info << "target angle [rad]: " << RodriguesVectorFromMatrix( Rtarget ) << " target angular velocity [rad/s]: " << ( ( Rr.T() & Rpre) & (RodriguesVectorFromMatrix( preRtarget )/dt) ) << endl;
	Info << "current angle [rad]: " << RodriguesVectorFromMatrix( rRb ) << " current angular velocity [rad/s]: " << angular_vel << endl;

	Info << "target difference [rad]: " << RodVector << " target difference velocity [rad/s]: " << RodVVector << endl;
	Info << "moment: " << moment << " P " << weight * gain_[0] * RodVector << " D " << weight * gain_[1] * RodVVector  << endl;

Info << "gain " << gain_ << endl; 
Info << "moment: " << weight * ( gain_[0] * RodVector + gain_[1] * RodVVector ) << 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::fishlocomotionCOM::read
(
    const dictionary& dict
)
{
    restraint::read(dict);

    coeffs_.readEntry("bodyLength", bodyLength_);
    coeffs_.readEntry("frequency", freq_);
    coeffs_.readEntry("waveLength", lambda_);
    coeffs_.readEntry("carangiform", carangiform_);
    coeffs_.readEntry("rolling", rolling_);
    coeffs_.readEntry("gain", gain_);
    coeffs_.readEntry("x_origin", x_origin_);
    coeffs_.readEntry("initialPitch", initialPitch_);
    coeffs_.readEntry("relaxationTime", relaxationTime_);
    coeffs_.readEntry("reaction", reaction_);

    return true;
}


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

    os.writeEntry("bodyLength", bodyLength_);
    os.writeEntry("frequency", freq_);
    os.writeEntry("lambda", lambda_);
    os.writeEntry("carangiform", carangiform_);
    os.writeEntry("rolling", rolling_);
    os.writeEntry("gain", gain_);
    os.writeEntry("x_origin", x_origin_);
    os.writeEntry("initialPitch", initialPitch_);
    os.writeEntry("relaxationTime", relaxationTime_);
    os.writeEntry("reaction", reaction_);
}


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