/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | www.openfoam.com
     \\/     M anipulation  |
-------------------------------------------------------------------------------
    Copyright (C) 2011-2016 OpenFOAM Foundation
    Copyright (C) 2019-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 "fv.H"
#include "gpusnGradScheme.H"
#include "volgpuFields.H"
#include "surfacegpuFields.H"
#include "HashTable.H"

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

namespace Foam
{

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

namespace fv
{

// * * * * * * * * * * * * * * * * * Selectors * * * * * * * * * * * * * * * //

template<class Type>
tmp<gpusnGradScheme<Type>> gpusnGradScheme<Type>::New
(
    const gpufvMesh& mesh,
    Istream& schemeData
)
{
    if (fv::debug)
    {
        InfoInFunction << "Constructing snGradScheme<Type>" << endl;
    }

    if (schemeData.eof())
    {
        FatalIOErrorInFunction(schemeData)
            << "Discretisation scheme not specified"
            << nl << nl
            << "Valid schemes are :" << nl
            << MeshConstructorTablePtr_->sortedToc()
            << exit(FatalIOError);
    }

    const word schemeName(schemeData);

    auto* ctorPtr = MeshConstructorTable(schemeName);

    if (!ctorPtr)
    {
        FatalIOErrorInLookup
        (
            schemeData,
            "discretisation",
            schemeName,
            *MeshConstructorTablePtr_
        ) << exit(FatalIOError);
    }

    return ctorPtr(mesh, schemeData);
}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //
template<class Type>
struct snGradFunctor
{
    __host__ __device__
    Type operator()(const scalar& d, const thrust::tuple<Type,Type>& t)
    {
        return d*(thrust::get<0>(t) - thrust::get<1>(t));
    }
};

template<class Type>
tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>>
gpusnGradScheme<Type>::snGrad
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& vf,
    const tmp<surfaceScalargpuField>& tdeltaCoeffs,
    const word& snGradName
)
{
    const gpufvMesh& mesh = vf.mesh();

    // construct GeometricField<Type, fvsPatchField, surfaceMesh>
    tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>> tsf
    (
        new GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>
        (
            IOobject
            (
                snGradName + "("+vf.name()+')',
                vf.instance(),
                vf.mesh().hostmesh(),
                IOobject::NO_READ,
                IOobject::NO_WRITE
            ),
            mesh,
            vf.dimensions()*tdeltaCoeffs().dimensions()
        )
    );
    GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>& ssf = tsf.ref();
    ssf.setOriented();

    // set reference to difference factors array
    const scalargpuField& deltaCoeffs = tdeltaCoeffs();

    // owner/neighbour addressing
    const labelgpuList& owner = mesh.owner();
    const labelgpuList& neighbour = mesh.neighbour();

    thrust::transform(deltaCoeffs.begin(),deltaCoeffs.end(),
                      thrust::make_zip_iterator(thrust::make_tuple(thrust::make_permutation_iterator(vf.primitiveField().begin(),neighbour.begin()),
                                                                   thrust::make_permutation_iterator(vf.primitiveField().begin(),owner.begin())
                                                                  )
                                               ),
                     ssf.primitiveFieldRef().begin(),
                     snGradFunctor<Type>()
                     );

    typename GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>::
        Boundary& ssfbf = ssf.boundaryFieldRef();

    forAll(vf.boundaryField(), patchi)
    {
        const fvPatchgpuField<Type>& pvf = vf.boundaryField()[patchi];

        if (pvf.coupled())
        {
            ssfbf[patchi] = pvf.snGrad(tdeltaCoeffs().boundaryField()[patchi]);
        }
        else
        {
            ssfbf[patchi] = pvf.snGrad();
        }
    }

    return tsf;
}


template<class Type>
tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>>
gpusnGradScheme<Type>::sndGrad
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& vf,
    const word& sndGradName
)
{
    return snGrad(vf, vf.mesh().nonOrthDeltaCoeffs(), sndGradName);
}


template<class Type>
tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>>
gpusnGradScheme<Type>::snGrad
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& vf
) const
{
    tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>> tsf
    (
        snGrad(vf, deltaCoeffs(vf))
    );

    if (corrected())
    {
        tsf.ref() += correction(vf);
    }

    return tsf;
}


template<class Type>
tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>>
gpusnGradScheme<Type>::snGrad
(
    const tmp<GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>>& tvf
) const
{
    tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>> tsf
    (
        snGrad(tvf())
    );

    tsf.clear();
    return tsf;
}


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

} // End namespace fv

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

} // End namespace Foam

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