/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | Multiphase Code Repository by HZDR
  ======   //   ||  || ===//   | Website: https://doi.org/10.14278/rodare.767
  ||  ||  //    ||  // || \\   | License: GPL-3.0-or-later
  ==  == ====== ====   ==  ==  |
-------------------------------------------------------------------------------
License
    This file is part of the Multiphase Code Repository by HZDR.

    Copyright (C) 2025 by Helmholtz-Zentrum Dresden-Rossendorf e.V. (HZDR),
    Website: https://hzdr.de

    Multiphase Code Repository by HZDR is based on the free software for
    computational fluid dynamics (CFD) from the OpenFOAM Foundation.
    Copyright (C) 2025 by OpenFOAM Foundation, Website: https://openfoam.org

    If you are interested in which files are original OpenFOAM Foundation
    files, which OpenFOAM Foundation files were modified, and which files were
    newly created, see FILES.md.

    Multiphase Code Repository by HZDR 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.

    Multiphase Code Repository by HZDR 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 the Multiphase Code Repository by HZDR. If not, see
    <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "inducedTurbulence.H"
#include "addToRunTimeSelectionTable.H"
#include "fvmSup.H"
#include "kOmegaSSTLangtrySjolander.H"

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

namespace Foam
{
namespace fv
{
    defineTypeNameAndDebug(inducedTurbulence, 0);

    addToRunTimeSelectionTable
    (
        fvModel,
        inducedTurbulence,
        dictionary
    );
}
}


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

Foam::fv::inducedTurbulence::inducedTurbulence
(
    const word& sourceName,
    const word& modelType,
    const fvMesh& mesh,
    const dictionary& dict
)
:
    fvModel(sourceName, modelType, mesh, dict),
    phaseName_(dict.lookup("phase")),
    phase_
    (
        mesh.lookupObject<phaseModel>(IOobject::groupName("alpha", phaseName_))
    ),
    dispersedPhaseNames_(dict.lookup<wordList>("dispersedPhases")),
    interfaces_(dispersedPhaseNames_.size()),
    blendingMethods_(dispersedPhaseNames_.size()),
    inducedTurbulenceModels_(dispersedPhaseNames_.size()),
    alphas_
    (
        phase_.fluid().phases().PtrList
        <
            phaseModel
        >::convert<const volScalarField>()
    ),
    isotropicRSource_(dict.lookupOrDefault<Switch>("isotropicRSource", true)),
    turbulence_
    (
        mesh.lookupObject
        <
            phaseCompressible::momentumTransportModel
        >
        (
            IOobject::groupName
            (
                momentumTransportModel::typeName,
                phaseName_
            )
        )
    )
{
    const word RName(IOobject::groupName("R", phaseName_));
    const word kName(IOobject::groupName("k", phaseName_));
    const word epsilonName(IOobject::groupName("epsilon", phaseName_));
    const word omegaName(IOobject::groupName("omega", phaseName_));

    if (mesh.foundObject<volSymmTensorField>(RName))
    {
        fieldNames_.append(RName);
    }
    else if (mesh.foundObject<volScalarField>(kName))
    {
        fieldNames_.append(kName);
    }
    else
    {
        FatalIOErrorInFunction(dict)
            << "Cannot find either " << RName << " or " << kName
            << " field for fvModel " << typeName << exit(FatalIOError);
    }

    if (mesh.foundObject<volScalarField>(epsilonName))
    {
        fieldNames_.append(epsilonName);
    }
    else if (mesh.foundObject<volScalarField>(omegaName))
    {
        fieldNames_.append(omegaName);
    }
    else
    {
        FatalIOErrorInFunction(dict)
            << "Cannot find either " << epsilonName << " or " << omegaName
            << " field for fvModel " << typeName << exit(FatalIOError);
    }

    const dictionary& blendingDict = phase_.fluid().subDict("blending");

    if (!dispersedPhaseNames_.size())
    {
        FatalIOErrorInFunction(dict)
            << "No dispersed phases provided for " << typeName
            << exit(FatalIOError);
    }
    else
    {
        forAll(dispersedPhaseNames_, i)
        {
            const phaseModel& dispersedPhase
            (
                mesh.lookupObject<phaseModel>
                (
                    IOobject::groupName("alpha", dispersedPhaseNames_[i])
                )
            );

            interfaces_.set
            (
                i,
                new dispersedPhaseInterface(dispersedPhase, phase_)
            );

            inducedTurbulenceModels_.set
            (
                i,
                inducedTurbulenceModel::New(dict, interfaces_[i]).ptr()
            );

            blendingMethods_.set
            (
                i,
                blendingMethod::New
                (
                    typeName,
                    blendingDict.found(typeName)
                  ? blendingDict.subDict(typeName)
                  : blendingDict.subDict("default"),
                    interfaces_[i]
                )
            );
        }
    }
}


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

Foam::wordList Foam::fv::inducedTurbulence::addSupFields() const
{
    return fieldNames_;
}


void Foam::fv::inducedTurbulence::addSup
(
    const volScalarField& alpha,
    const volScalarField& rho,
    const volScalarField& field,
    fvMatrix<scalar>& eqn
) const
{
    if (debug)
    {
        Info<< type() << ": applying source to " << eqn.psi().name() << endl;
    }

    if
    (
        field.name() == IOobject::groupName("k", phase_.name())
    )
    {
        forAll(inducedTurbulenceModels_, i)
        {
            eqn += blendingFactor(i)*inducedTurbulenceModels_[i].kSource();
        }
    }
    else if
    (
        field.name() == IOobject::groupName("epsilon", phase_.name())
    )
    {
        forAll(inducedTurbulenceModels_, i)
        {
            eqn +=
                blendingFactor(i)*inducedTurbulenceModels_[i].epsilonSource();
        }
    }
    else if (field.name() == IOobject::groupName("omega", phase_.name()))
    {
        forAll(inducedTurbulenceModels_, i)
        {
            if
            (
                isA
                <
                    Foam::RASModels::kOmegaSSTLangtrySjolander
                    <
                        Foam::phaseCompressibleMomentumTransportModel
                    >
                >(turbulence_)
            )
            {
                const Foam::RASModels::kOmegaSSTLangtrySjolander
                <
                    Foam::phaseCompressibleMomentumTransportModel
                >& turbulence = dynamic_cast
                <
                    const Foam::RASModels::kOmegaSSTLangtrySjolander
                <
                    Foam::phaseCompressibleMomentumTransportModel
                >&
                >(turbulence_);

                const tmp<volScalarField> k = turbulence_.k();
                const volScalarField& omega = eqn.psi();

                tmp<volScalarField> tBetaStar
                (
                    volScalarField::New
                    (
                        "betaStar",
                        phase_.mesh(),
                        dimensionedScalar(dimensionSet(0, 0, 0, 0, 0), 1)
                    )
                );

                volScalarField& betaStar = tBetaStar.ref();

                const volScalarField CDkOmega
                (
                    (2*turbulence.alphaOmega2_)
                   *(fvc::grad(k) & fvc::grad(omega))
                   /omega
                );

                const volScalarField F1(turbulence.F1(CDkOmega));
                betaStar.internalFieldRef() = turbulence.betaStar(F1);

                eqn +=
                    blendingFactor(i)
                   *(
                        inducedTurbulenceModels_[i].epsilonSource()/(betaStar*k)
                      - fvm::Sp(inducedTurbulenceModels_[i].kSource()/k, omega)
                    );
            }
            else
            {
                eqn +=
                    blendingFactor(i)
                   *inducedTurbulenceModels_[i].omegaSource(eqn);
            }
        }
    }
    else
    {
        FatalErrorInFunction
            << "Support for field " << field.name() << " is not implemented"
            << exit(FatalError);
    }
}


void Foam::fv::inducedTurbulence::addSup
(
    const volScalarField& alpha,
    const volScalarField& rho,
    const volScalarField& field,
    fvMatrix<symmTensor>& eqn
) const
{
    if (debug)
    {
        Info<< type() << ": applying source to " << eqn.psi().name() << endl;
    }

    if
    (
        field.name() == IOobject::groupName("R", phase_.name())
    )
    {
        forAll(inducedTurbulenceModels_, i)
        {
            if (isotropicRSource_)
            {
                eqn +=
                    blendingFactor(i)
                   *2.0/3.0*inducedTurbulenceModels_[i].kSource()
                   *symmTensor::I;
            }
            else
            {
                const dimensionedScalar smallU("smallU", dimVelocity, 1e-16);

                const volVectorField Ur_hat
                (
                    interfaces_[i].Ur()/(interfaces_[i].magUr() + smallU)
                );

                const volSymmTensorField uu(symm(Ur_hat*Ur_hat));

                eqn +=
                    blendingFactor(i)
                   *0.5*inducedTurbulenceModels_[i].kSource()
                   *(symmTensor::I + uu);
            }
        }
    }
    else
    {
        FatalErrorInFunction
            << "Support for field " << field.name() << " is not implemented"
            << exit(FatalError);
    }
}


Foam::tmp<Foam::volScalarField> Foam::fv::inducedTurbulence::blendingFactor
(
    const label i
) const
{
    return
        interfaces_[i].dispersed().index() < interfaces_[i].continuous().index()
      ? blendingMethods_[i].f1DispersedIn2(alphas_)
      : blendingMethods_[i].f2DispersedIn1(alphas_);
}


void Foam::fv::inducedTurbulence::topoChange(const polyTopoChangeMap&)
{}


void Foam::fv::inducedTurbulence::mapMesh(const polyMeshMap& map)
{}


void Foam::fv::inducedTurbulence::distribute
(
    const polyDistributionMap&
)
{}


bool Foam::fv::inducedTurbulence::movePoints()
{
    return true;
}


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