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

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

template<class Type>
Foam::tmp<Foam::gpulimitedSurfaceInterpolationScheme<Type>>
Foam::gpulimitedSurfaceInterpolationScheme<Type>::New
(
    const gpufvMesh& mesh,
    Istream& schemeData
)
{
    if (gpusurfaceInterpolation::debug)
    {
        InfoInFunction
            << "Constructing limitedSurfaceInterpolationScheme<Type>" << endl;
    }

    if (schemeData.eof())
    {
        FatalIOErrorInFunction(schemeData)
            << "Discretisation scheme not specified"
            << endl << endl
            << "Valid schemes are :" << endl
            << 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);
}


template<class Type>
Foam::tmp<Foam::gpulimitedSurfaceInterpolationScheme<Type>>
Foam::gpulimitedSurfaceInterpolationScheme<Type>::New
(
    const gpufvMesh& mesh,
    const surfaceScalargpuField& faceFlux,
    Istream& schemeData
)
{
    if (gpusurfaceInterpolation::debug)
    {
        InfoInFunction
            << "Constructing limitedSurfaceInterpolationScheme<Type>"
            << endl;
    }

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

    const word schemeName(schemeData);

    auto* ctorPtr = MeshFluxConstructorTable(schemeName);

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

    return ctorPtr(mesh, faceFlux, schemeData);
}


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

template<class Type>
Foam::gpulimitedSurfaceInterpolationScheme<Type>::
~gpulimitedSurfaceInterpolationScheme()
{}


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

namespace Foam
{
struct limitedSurfaceInterpolationSchemeWeightsFunctor{
    __host__ __device__
    scalar operator()(const thrust::tuple<scalar,scalar,scalar>& t){
        return thrust::get<0>(t)*thrust::get<1>(t)
          + (1.0 - thrust::get<0>(t))*pos0(thrust::get<2>(t));
    }
};
}


template<class Type>
Foam::tmp<Foam::surfaceScalargpuField>
Foam::gpulimitedSurfaceInterpolationScheme<Type>::weights
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& phi,
    const surfaceScalargpuField& CDweights,
    tmp<surfaceScalargpuField> tLimiter
) const
{
    // Note that here the weights field is initialised as the limiter
    // from which the weight is calculated using the limiter value
    surfaceScalargpuField& Weights = tLimiter.ref();

    scalargpuField& pWeights = Weights.primitiveFieldRef();

    /*forAll(pWeights, face)
    {
        pWeights[face] =
            pWeights[face]*CDweights[face]
          + (1.0 - pWeights[face])*pos0(faceFlux_[face]);
    }*/

    thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(pWeights.begin(),CDweights.field().begin(),faceFlux_.field().begin())),
                      thrust::make_zip_iterator(thrust::make_tuple(pWeights.end(),CDweights.field().end(),faceFlux_.field().end())),
                      pWeights.begin(),
                      limitedSurfaceInterpolationSchemeWeightsFunctor());

    surfaceScalargpuField::Boundary& bWeights =
        Weights.boundaryFieldRef();

    forAll(bWeights, patchi)
    {
        scalargpuField& pWeights = bWeights[patchi];

        const scalargpuField& pCDweights = CDweights.boundaryField()[patchi];
        const scalargpuField& pFaceFlux = faceFlux_.boundaryField()[patchi];

        /*forAll(pWeights, face)
        {
            pWeights[face] =
                pWeights[face]*pCDweights[face]
              + (1.0 - pWeights[face])*pos0(pFaceFlux[face]);
        }*/
       
        thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(pWeights.begin(),pCDweights.begin(),pFaceFlux.begin())),
                      thrust::make_zip_iterator(thrust::make_tuple(pWeights.end(),pCDweights.end(),pFaceFlux.end())),
                      pWeights.begin(),
                      limitedSurfaceInterpolationSchemeWeightsFunctor());
    }

    return tLimiter;
}

template<class Type>
Foam::tmp<Foam::surfaceScalargpuField>
Foam::gpulimitedSurfaceInterpolationScheme<Type>::weights
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& phi
) const
{
    return this->weights
    (
        phi,
        this->mesh().gpusurfaceInterpolation::weights(),
        this->limiter(phi)
    );
}

template<class Type>
Foam::tmp<Foam::GeometricgpuField<Type, Foam::fvsPatchgpuField, Foam::gpusurfaceMesh>>
Foam::gpulimitedSurfaceInterpolationScheme<Type>::flux
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& phi
) const
{
    return faceFlux_*this->interpolate(phi);
}


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