/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | www.openfoam.com
     \\/     M anipulation  |
-------------------------------------------------------------------------------
    Copyright (C) 2020-2021 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 "basicgpuFvGeometryScheme.H"
#include "addToRunTimeSelectionTable.H"
#include "surfacegpuFields.H"
#include "volgpuFields.H"

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

namespace Foam
{
    defineTypeNameAndDebug(basicgpuFvGeometryScheme, 0);
    addToRunTimeSelectionTable(gpufvGeometryScheme, basicgpuFvGeometryScheme, dict);
}


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

Foam::basicgpuFvGeometryScheme::basicgpuFvGeometryScheme
(
    const gpufvMesh& mesh,
    const dictionary& dict
)
:
    gpufvGeometryScheme(mesh, dict)
{}


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

void Foam::basicgpuFvGeometryScheme::movePoints()
{
    if (debug)
    {
        Pout<< "basicFvGeometryScheme::movePoints() : "
            << "recalculating primitiveMesh centres" << endl;
    }
    // Use lower level to calculate the geometry
    const_cast<fvMesh&>(mesh_.hostmesh()).primitiveMesh::updateGeom();
}

	namespace Foam
	{
	
	struct surfaceInterpolationMakeWeightsFunctor
	{
		__host__ __device__
		scalar operator()(const thrust::tuple<vector,vector,vector,vector>& t)
		{
			scalar SfdOwn = mag(thrust::get<0>(t) & (thrust::get<1>(t) - thrust::get<2>(t)));
			scalar SfdNei = mag(thrust::get<0>(t) & (thrust::get<3>(t) - thrust::get<1>(t)));
			if(mag(SfdOwn + SfdNei) > ROOTVSMALL)
			{
				return SfdNei/(SfdOwn + SfdNei);
			}
			else
			{
				return 0.5;
			}
		}
	};
	
	}

Foam::tmp<Foam::surfaceScalargpuField> Foam::basicgpuFvGeometryScheme::weights() const
{
    if (debug)
    {
        Pout<< "basicgpuFvGeometryScheme::weights() : "
            << "Constructing weighting factors for face interpolation"
            << endl;
    }

    tmp<surfaceScalargpuField> tweights
    (
        new surfaceScalargpuField
        (
            IOobject
            (
                "weights",
                mesh_.hostmesh().pointsInstance(),
                mesh_.hostmesh(),
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false // Do not register
            ),
            mesh_,
            dimless
        )
    );
    surfaceScalargpuField& weights = tweights.ref();
    weights.setOriented();

    // Set local references to mesh data
    // Note that we should not use fvMesh sliced fields at this point yet
    // since this causes a loop when generating weighting factors in
    // coupledFvPatchField evaluation phase
    const labelgpuList& owner = mesh_.owner();
    const labelgpuList& neighbour = mesh_.neighbour();

    const vectorgpuField& Cf = mesh_.hostmesh().gpuFaceCentres();
    const vectorgpuField& C = mesh_.hostmesh().gpuCellCentres();
    const vectorgpuField& Sf = mesh_.hostmesh().gpuFaceAreas();

    // ... and reference to the internal field of the weighting factors
    scalargpuField& w = weights.primitiveFieldRef();

    thrust::transform
    (
        thrust::make_zip_iterator(thrust::make_tuple
        (
            Sf.begin(),
            Cf.begin(),
            thrust::make_permutation_iterator
            (
                C.begin(),
                owner.begin()
            ),
            thrust::make_permutation_iterator
            (
                C.begin(),
                neighbour.begin()
            )
        )),
        thrust::make_zip_iterator(thrust::make_tuple
        (
            Sf.begin()+owner.size(),
            Cf.begin()+owner.size(),
            thrust::make_permutation_iterator
            (
                C.begin(),
                owner.end()
            ),
            thrust::make_permutation_iterator
            (
                C.begin(),
                neighbour.end()
            )
        )),
        w.begin(),
        surfaceInterpolationMakeWeightsFunctor()
    );

    surfaceScalargpuField::Boundary& wBf = weights.boundaryFieldRef();

    forAll(mesh_.boundary(), patchi)
    {
        mesh_.boundary()[patchi].makeWeights(wBf[patchi]);
    }

    if (debug)
    {
        Pout<< "basicFvGeometryScheme::weights : "
            << "Finished constructing weighting factors for face interpolation"
            << endl;
    }
    return tweights;
}

namespace Foam
{

struct surfaceInterpolationDeltaCoeffsFunctor
{
    __host__ __device__
    scalar operator()(const vector& cn, const vector& co)
    {
        return 1.0/mag(cn - co);
    }
};

}

Foam::tmp<Foam::surfaceScalargpuField>
Foam::basicgpuFvGeometryScheme::deltaCoeffs() const
{
    if (debug)
    {
        Pout<< "basicFvGeometryScheme::deltaCoeffs() : "
            << "Constructing differencing factors array for face gradient"
            << endl;
    }

    // Force the construction of the weighting factors
    // needed to make sure deltaCoeffs are calculated for parallel runs.
    (void)mesh_.weights();

    tmp<surfaceScalargpuField> tdeltaCoeffs
    (
        new surfaceScalargpuField
        (
            IOobject
            (
                "deltaCoeffs",
                mesh_.hostmesh().pointsInstance(),
                mesh_.hostmesh(),
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false // Do not register
            ),
            mesh_,
            dimless/dimLength
        )
    );
    surfaceScalargpuField& deltaCoeffs = tdeltaCoeffs.ref();
    deltaCoeffs.setOriented();


    // Set local references to mesh data
    const volVectorgpuField& C = mesh_.C();
    const labelgpuList& owner = mesh_.owner();
    const labelgpuList& neighbour = mesh_.neighbour();

    thrust::transform
    (
        thrust::make_permutation_iterator
        (
            C.primitiveField().begin(),
            neighbour.begin()
        ),
        thrust::make_permutation_iterator
        (
            C.primitiveField().begin(),
            neighbour.end()
        ),
        thrust::make_permutation_iterator
        (
            C.primitiveField().begin(),
            owner.begin()
        ),
        deltaCoeffs.primitiveFieldRef().begin(),
        surfaceInterpolationDeltaCoeffsFunctor()
    );

    surfaceScalargpuField::Boundary& deltaCoeffsBf =
        deltaCoeffs.boundaryFieldRef();

    forAll(deltaCoeffsBf, patchi)
    {
        const gpufvPatch& p = mesh_.boundary()[patchi];
        deltaCoeffsBf[patchi] = 1.0/mag(p.delta());

        // Optionally correct
        p.makeDeltaCoeffs(deltaCoeffsBf[patchi]);
    }

    return tdeltaCoeffs;
}

namespace Foam
{

struct surfaceInterpolationNonOrtoDeltaCoeffsFunctor
{
    __host__ __device__
    scalar operator()(const thrust::tuple<vector,vector,vector,scalar>& t)
    {

        vector delta = thrust::get<0>(t) - thrust::get<1>(t);
        vector unitArea = thrust::get<2>(t)/thrust::get<3>(t);
        return 1.0/max(unitArea & delta, 0.05*mag(delta));
    }
};

struct surfaceInterpolationPatchNonOrtoDeltaCoeffsFunctor
{
    __host__ __device__
    scalar operator()(const thrust::tuple<vector,vector,scalar,scalar>& t)
    {
        vector unitArea = thrust::get<1>(t)/thrust::get<2>(t);

        return 1.0/max(unitArea & thrust::get<0>(t), 0.05*mag(thrust::get<0>(t)));
    }
};

}

Foam::tmp<Foam::surfaceScalargpuField>
Foam::basicgpuFvGeometryScheme::nonOrthDeltaCoeffs() const
{
    if (debug)
    {
        Pout<< "basicFvGeometryScheme::nonOrthDeltaCoeffs() : "
            << "Constructing differencing factors array for face gradient"
            << endl;
    }

    // Force the construction of the weighting factors
    // needed to make sure deltaCoeffs are calculated for parallel runs.
    weights();

    tmp<surfaceScalargpuField> tnonOrthDeltaCoeffs
    (
        new surfaceScalargpuField
        (
            IOobject
            (
                "nonOrthDeltaCoeffs",
                mesh_.hostmesh().pointsInstance(),
                mesh_.hostmesh(),
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false // Do not register
            ),
            mesh_,
            dimless/dimLength
        )
    );
    surfaceScalargpuField& nonOrthDeltaCoeffs = tnonOrthDeltaCoeffs.ref();
    nonOrthDeltaCoeffs.setOriented();


    // Set local references to mesh data
    const volVectorgpuField& C = mesh_.C();
    const labelgpuList& owner = mesh_.owner();
    const labelgpuList& neighbour = mesh_.neighbour();
    const surfaceVectorgpuField& Sf = mesh_.Sf();
    const surfaceScalargpuField& magSf = mesh_.magSf();

    thrust::transform
    (
        thrust::make_zip_iterator(thrust::make_tuple
        (
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                neighbour.begin()
            ),
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                owner.begin()
            ),
            Sf.primitiveField().begin(),
            magSf.primitiveField().begin()
        )),
        thrust::make_zip_iterator(thrust::make_tuple
        (
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                neighbour.end()
            ),
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                owner.end()
            ),
            Sf.primitiveField().begin()+owner.size(),
            magSf.primitiveField().begin()+owner.size()
        )),
        nonOrthDeltaCoeffs.primitiveFieldRef().begin(),
        surfaceInterpolationNonOrtoDeltaCoeffsFunctor()
    );

    surfaceScalargpuField::Boundary& nonOrthDeltaCoeffsBf =
        nonOrthDeltaCoeffs.boundaryFieldRef();

    forAll(nonOrthDeltaCoeffsBf, patchi)
    {
        fvsPatchScalargpuField& patchDeltaCoeffs = nonOrthDeltaCoeffsBf[patchi];

        const gpufvPatch& p = patchDeltaCoeffs.patch();

        const vectorgpuField patchDeltas(mesh_.boundary()[patchi].delta());

        thrust::transform
            (
                thrust::make_zip_iterator(thrust::make_tuple
                (
                    patchDeltas.begin(),
                    Sf.boundaryField()[patchi].begin(),
                    magSf.boundaryField()[patchi].begin(),
                    patchDeltaCoeffs.begin()
                )),
                thrust::make_zip_iterator(thrust::make_tuple
                (
                    patchDeltas.end(),
                    Sf.boundaryField()[patchi].end(),
                    magSf.boundaryField()[patchi].end(),
                    patchDeltaCoeffs.end()
                )),
                patchDeltaCoeffs.begin(),
                surfaceInterpolationPatchNonOrtoDeltaCoeffsFunctor()
            );

        // Optionally correct
        p.makeNonOrthoDeltaCoeffs(patchDeltaCoeffs);
    }
    return tnonOrthDeltaCoeffs;
}

namespace Foam
{

struct surfaceInterpolationNonOrtoCorrectionVectorsFunctor
{
    __host__ __device__
    vector operator()(const thrust::tuple<vector,vector,vector,scalar,scalar>& t)
    {

        vector delta = thrust::get<0>(t) - thrust::get<1>(t);
        vector unitArea = thrust::get<2>(t)/thrust::get<3>(t);

        return unitArea - delta*thrust::get<4>(t);
    }
};

struct surfaceInterpolationPatchNonOrtoCorrectionVectorsFunctor
{
    __host__ __device__
    vector operator()(const thrust::tuple<vector,vector,scalar,scalar>& t)
    {
        vector unitArea = thrust::get<1>(t)/thrust::get<2>(t);

        return unitArea - thrust::get<0>(t)*thrust::get<3>(t);
    }
};

}

Foam::tmp<Foam::surfaceVectorgpuField>
Foam::basicgpuFvGeometryScheme::nonOrthCorrectionVectors() const
{
    if (debug)
    {
        Pout<< "surfaceInterpolation::makeNonOrthCorrectionVectors() : "
            << "Constructing non-orthogonal correction vectors"
            << endl;
    }

    tmp<surfaceVectorgpuField> tnonOrthCorrectionVectors
    (
        new surfaceVectorgpuField
        (
            IOobject
            (
                "nonOrthCorrectionVectors",
                mesh_.hostmesh().pointsInstance(),
                mesh_.hostmesh(),
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false // Do not register
            ),
            mesh_,
            dimless
        )
    );
    surfaceVectorgpuField& corrVecs = tnonOrthCorrectionVectors.ref();
    corrVecs.setOriented();

    // Set local references to mesh data
    const volVectorgpuField& C = mesh_.C();
    const labelgpuList& owner = mesh_.owner();
    const labelgpuList& neighbour = mesh_.neighbour();
    const surfaceVectorgpuField& Sf = mesh_.Sf();
    const surfaceScalargpuField& magSf = mesh_.magSf();
    tmp<surfaceScalargpuField> tNonOrthDeltaCoeffs(nonOrthDeltaCoeffs());
    const surfaceScalargpuField& NonOrthDeltaCoeffs = tNonOrthDeltaCoeffs();

    thrust::transform
    (
        thrust::make_zip_iterator(thrust::make_tuple
        (
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                neighbour.begin()
            ),
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                owner.begin()
            ),
            Sf.primitiveField().begin(),
            magSf.primitiveField().begin(),
            NonOrthDeltaCoeffs.primitiveField().begin()
        )),
        thrust::make_zip_iterator(thrust::make_tuple
        (
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                neighbour.begin()+owner.size()
            ),
            thrust::make_permutation_iterator
            (
                C.primitiveField().begin(),
                owner.end()
            ),
            Sf.primitiveField().end(),
            magSf.primitiveField().end(),
            NonOrthDeltaCoeffs.primitiveField().end()
        )),
        corrVecs.primitiveFieldRef().begin(),
        surfaceInterpolationNonOrtoCorrectionVectorsFunctor()
    );

    // Boundary correction vectors set to zero for boundary patches
    // and calculated consistently with internal corrections for
    // coupled patches

    surfaceVectorgpuField::Boundary& corrVecsBf = corrVecs.boundaryFieldRef();

    forAll(corrVecsBf, patchi)
    {
        fvsPatchVectorgpuField& patchCorrVecs = corrVecsBf[patchi];

        const gpufvPatch& p = patchCorrVecs.patch();

        if (!patchCorrVecs.coupled())
        {
            patchCorrVecs = Zero;
        }
        else
        {
            const fvsPatchScalargpuField& patchNonOrthDeltaCoeffs =
                NonOrthDeltaCoeffs.boundaryField()[patchi];

            const vectorgpuField patchDeltas(mesh_.boundary()[patchi].delta());

            thrust::transform
            (
                thrust::make_zip_iterator(thrust::make_tuple
                (
                    patchDeltas.begin(),
                    Sf.boundaryField()[patchi].begin(),
                    magSf.boundaryField()[patchi].begin(),
                    patchNonOrthDeltaCoeffs.begin()
                )),
                thrust::make_zip_iterator(thrust::make_tuple
                (
                    patchDeltas.end(),
                    Sf.boundaryField()[patchi].end(),
                    magSf.boundaryField()[patchi].end(),
                    patchNonOrthDeltaCoeffs.end()
                )),
                patchCorrVecs.begin(),
                surfaceInterpolationPatchNonOrtoCorrectionVectorsFunctor()
            );
        }

        // Optionally correct
        p.makeNonOrthoCorrVectors(patchCorrVecs);
    }

    if (debug)
    {
        Pout<< "surfaceInterpolation::makeNonOrthCorrectionVectors() : "
            << "Finished constructing non-orthogonal correction vectors"
            << endl;
    }
    return tnonOrthCorrectionVectors;
}


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