/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | www.openfoam.com
     \\/     M anipulation  |
-------------------------------------------------------------------------------
    Copyright (C) 2011-2018 OpenFOAM Foundation
    Copyright (C) 2017-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 "HashTable.H"
#include "gpusurfaceInterpolate.H"
#include "gpufvMatrix.H"
#include "cyclicAMIgpuFvPatch.H"
#include "registerSwitch.H"

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

namespace Foam
{

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

namespace fv
{

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

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

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

    const word schemeName(schemeData);

    auto* ctorPtr = IstreamConstructorTable(schemeName);

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

    return ctorPtr(mesh, schemeData);
}


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

template<class Type>
tmp<GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>> gpuddtScheme<Type>::fvcDdt
(
    const volScalargpuField& alpha,
    const volScalargpuField& rho,
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& vf
)
{
    NotImplemented;

    return tmp<GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>>
    (
        GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>::null()
    );
}


template<class Type>
tmp<gpufvMatrix<Type>> gpuddtScheme<Type>::fvmDdt
(
    const volScalargpuField& alpha,
    const volScalargpuField& rho,
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& vf
)
{
    NotImplemented;

    return tmp<gpufvMatrix<Type>>::New
    (
        vf,
        alpha.dimensions()*rho.dimensions()
        *vf.dimensions()*dimVol/dimTime
    );
}


template<class Type>
tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>> gpuddtScheme<Type>::fvcDdt
(
    const GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>& sf
)
{
    NotImplemented;

    return tmp<GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>>
    (
        GeometricgpuField<Type, fvsPatchgpuField, gpusurfaceMesh>::null()
    );
}



template<class Type>
tmp<surfaceScalargpuField> gpuddtScheme<Type>::fvcDdtPhiCoeff
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& U,
    const fluxFieldType& phi,
    const fluxFieldType& phiCorr
)
{
    if (fv::debug)
    {
        InfoInFunction << "Using standard version" << endl;
    }

    tmp<surfaceScalargpuField> tddtCouplingCoeff
    (
        new surfaceScalargpuField
        (
            IOobject
            (
                "ddtCouplingCoeff",
                U.mesh().time().timeName(),
                U.mesh().hostmesh()
            ),
            U.mesh(),
            dimensionedScalar("one", dimless, 1.0)
        )
    );

    surfaceScalargpuField& ddtCouplingCoeff = tddtCouplingCoeff.ref();

    if (ddtPhiCoeff_ < 0)
    {
        // v1712 and earlier
        ddtCouplingCoeff -= min
        (
            mag(phiCorr)
           /(mag(phi) + dimensionedScalar("small", phi.dimensions(), SMALL)),
            scalar(1)
        );
    }
    else
    {
        ddtCouplingCoeff =
            dimensionedScalar("ddtPhiCoeff", dimless, ddtPhiCoeff_);
    }

    surfaceScalargpuField::Boundary& ccbf = ddtCouplingCoeff.boundaryFieldRef();

    forAll(U.boundaryField(), patchi)
    {
        if
        (
            U.boundaryField()[patchi].fixesValue()
         || isA<cyclicAMIgpuFvPatch>(mesh().boundary()[patchi])
        )
        {
            ccbf[patchi] = 0.0;
        }
    }

    if (debug > 1)
    {
        InfoInFunction
            << "ddtCouplingCoeff mean max min = "
            << gAverage(ddtCouplingCoeff.primitiveField())
            << " " << gMax(ddtCouplingCoeff.primitiveField())
            << " " << gMin(ddtCouplingCoeff.primitiveField())
            << endl;
    }

    return tddtCouplingCoeff;
}


template<class Type>
tmp<surfaceScalargpuField> gpuddtScheme<Type>::fvcDdtPhiCoeffExperimental
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& U,
    const fluxFieldType& phi,
    const fluxFieldType& phiCorr
)
{
    if (fv::debug)
    {
        InfoInFunction << "Using experimental version" << endl;
    }

    tmp<surfaceScalargpuField> tddtCouplingCoeff
    (
        new surfaceScalargpuField
        (
            IOobject
            (
                "ddtCouplingCoeff",
                U.mesh().time().timeName(),
                U.mesh().hostmesh()
            ),
            U.mesh(),
            dimensionedScalar("one", dimless, 1.0)
        )
    );

    surfaceScalargpuField& ddtCouplingCoeff = tddtCouplingCoeff.ref();

    if (ddtPhiCoeff_ < 0)
    {
        // See note below re: commented code
        ddtCouplingCoeff -= min
        (
            //  mag(phiCorr)
            // *mesh().time().deltaT()*mag(mesh().deltaCoeffs())/mesh().magSf(),
            //  scalar(1)
            mag(phiCorr)
            *mesh().time().deltaT()*mesh().deltaCoeffs()/mesh().magSf(),
            scalar(1)
        );

        // Note: setting oriented to false to avoid having to use mag(deltaCoeffs)
        // - the deltaCoeffs field is always positive (scalars)
        ddtCouplingCoeff.setOriented(false);
    }
    else
    {
        ddtCouplingCoeff =
            dimensionedScalar("ddtPhiCoeff", dimless, ddtPhiCoeff_);
    }

    surfaceScalargpuField::Boundary& ccbf = ddtCouplingCoeff.boundaryFieldRef();

    forAll(U.boundaryField(), patchi)
    {
        if
        (
            U.boundaryField()[patchi].fixesValue()
         || isA<cyclicAMIgpuFvPatch>(mesh().boundary()[patchi])
        )
        {
            ccbf[patchi] = 0.0;
        }
    }

    if (debug > 1)
    {
        InfoInFunction
            << "ddtCouplingCoeff mean max min = "
            << gAverage(ddtCouplingCoeff.primitiveField())
            << " " << gMax(ddtCouplingCoeff.primitiveField())
            << " " << gMin(ddtCouplingCoeff.primitiveField())
            << endl;
    }

    return tddtCouplingCoeff;
}


template<class Type>
tmp<surfaceScalargpuField> gpuddtScheme<Type>::fvcDdtPhiCoeff
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& U,
    const fluxFieldType& phi,
    const fluxFieldType& phiCorr,
    const volScalargpuField& rho
)
{
    if (experimentalDdtCorr)
    {
        return
            fvcDdtPhiCoeffExperimental
            (
                U,
                phi,
                phiCorr/fvc::interpolate(rho)
            );
    }
    else
    {
        return fvcDdtPhiCoeff(U, phi, phiCorr);
    }
}


template<class Type>
tmp<surfaceScalargpuField> gpuddtScheme<Type>::fvcDdtPhiCoeff
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& U,
    const fluxFieldType& phi
)
{
    if (experimentalDdtCorr)
    {
        return
            fvcDdtPhiCoeffExperimental
            (
                U,
                phi,
                phi - fvc::dotInterpolate(mesh().Sf(), U)
            );
    }
    else
    {
        return
            fvcDdtPhiCoeff
            (
                U,
                phi,
                phi - fvc::dotInterpolate(mesh().Sf(), U)
            );
    }
}


template<class Type>
tmp<surfaceScalargpuField> gpuddtScheme<Type>::fvcDdtPhiCoeff
(
    const GeometricgpuField<Type, fvPatchgpuField, gpuvolMesh>& rhoU,
    const fluxFieldType& phi,
    const volScalargpuField& rho
)
{
    if (experimentalDdtCorr)
    {
        return fvcDdtPhiCoeffExperimental
        (
            rhoU,
            phi,
            (phi - fvc::dotInterpolate(mesh().Sf(), rhoU))
           /fvc::interpolate(rho)
        );
    }
    else
    {
        return fvcDdtPhiCoeff
        (
            rhoU,
            phi,
            (phi - fvc::dotInterpolate(mesh().Sf(), rhoU))
        );
    }
}


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

} // End namespace fv

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

} // End namespace Foam

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