/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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 "disperseGasZeroEquation.H"
#include "phaseSystem.H"

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

const Foam::phaseModel&
Foam::RASModels::disperseGasZeroEquation::continuousPhase() const
{
    const phaseSystem& fluid = phase_.fluid();

    if (continuousPhaseName_ == word::null)
    {
        if (fluid.movingPhases().size() != 2)
        {
            FatalIOErrorInFunction(coeffDict())
                << "Continuous phase name must be specified "
                << "when there are more than two moving phases."
                << exit(FatalIOError);
        }

        forAll(fluid.movingPhases(), movingPhasei)
        {
            const phaseModel& otherPhase = fluid.movingPhases()[movingPhasei];

            if (&otherPhase != &phase_)
            {
                return otherPhase;
            }
        }
    }

    return fluid.phases()[continuousPhaseName_];
}


const Foam::phaseCompressible::momentumTransportModel&
Foam::RASModels::disperseGasZeroEquation::continuousTurbulence() const
{
    return
        this->mesh().lookupType<phaseCompressible::momentumTransportModel>
        (
            continuousPhase().name()
        );
}


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

Foam::RASModels::disperseGasZeroEquation::disperseGasZeroEquation
(
    const volScalarField& alpha,
    const volScalarField& rho,
    const volVectorField& U,
    const surfaceScalarField& alphaRhoPhi,
    const surfaceScalarField& phi,
    const viscosity& viscosity,
    const word& type
)
:
    eddyViscosity<RASModel<phaseCompressible::momentumTransportModel>>
    (
        type,
        alpha,
        rho,
        U,
        alphaRhoPhi,
        phi,
        viscosity
    ),

    phase_(refCast<const phaseModel>(viscosity)),

    continuousPhaseName_
    (
        coeffDict().lookupOrDefault("continuousPhase", word::null)
    ),

    particleCrossTimeScale_
    (
        coeffDict().lookupOrDefault<Switch>("particleCrossTimeScale", true)
    ),
    CT_("CT", dimless, coeffDict().lookupOrDefault<scalar>("CT", 0.224)),
    CLambda_
    (
        "CLambda",
        dimless,
        coeffDict().lookupOrDefault<scalar>("CLambda", 0.234)
    ),

    scalingFactor_
    (
        IOobject
        (
            IOobject::groupName("scalingFactor", phase_.name()),
            this->runTime_.name(),
            this->mesh_,
            IOobject::NO_READ,
            IOobject::NO_WRITE
        ),
        this->mesh_,
        dimensionedScalar(dimless, 0)
    ),

    nuTurbScaled_
    (
        IOobject
        (
            IOobject::groupName("nuTurbScaled", phase_.name()),
            this->runTime_.name(),
            this->mesh_,
            IOobject::NO_READ,
            IOobject::NO_WRITE
        ),
        this->mesh_,
        dimensionedScalar(dimKinematicViscosity, 0)
    )
{}


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

bool Foam::RASModels::disperseGasZeroEquation::read()
{
    if
    (
        eddyViscosity<RASModel<phaseCompressible::momentumTransportModel>>::
        read()
    )
    {
        const dictionary& coeffDict = this->coeffDict();
        coeffDict.lookup("particleCrossTimeScale") >> particleCrossTimeScale_;
        CT_.readIfPresent(coeffDict);
        CLambda_.readIfPresent(coeffDict);

        return true;
    }
    else
    {
        return false;
    }
}


Foam::tmp<Foam::volScalarField>
Foam::RASModels::disperseGasZeroEquation::k() const
{
    return volScalarField::New
    (
        IOobject::groupName("k", phase_.name()),
        0.5*tr(R())
    );
}


Foam::tmp<Foam::volScalarField>
Foam::RASModels::disperseGasZeroEquation::epsilon() const
{
    NotImplemented;
    return tmp<volScalarField>(nullptr);
}


Foam::tmp<Foam::volScalarField>
Foam::RASModels::disperseGasZeroEquation::omega() const
{
    NotImplemented;
    return tmp<volScalarField>(nullptr);
}


Foam::tmp<Foam::volSymmTensorField>
Foam::RASModels::disperseGasZeroEquation::R() const
{
    return tmp<volSymmTensorField>
    (
        volSymmTensorField::New
        (
            IOobject::groupName("R", phase_.name()),
            scalingFactor_
           *(
                continuousTurbulence().nut()
               *dev(twoSymm(fvc::grad(continuousPhase().U())))
              + 2.0/3.0*I*continuousTurbulence().k()
            )
        )
    );
}


Foam::tmp<Foam::fvVectorMatrix>
Foam::RASModels::disperseGasZeroEquation::divDevTau
(
    volVectorField& U
) const
{
    const volVectorField& Ucontinuous = continuousPhase().URef();

    const volVectorField Urelative(U - Ucontinuous);

    tmp<fvVectorMatrix> divDevTauVisc =
        this->alpha_
       *(
           -fvm::laplacian(continuousPhase().fluidThermo().mu(), U)
          + fvc::laplacian(continuousPhase().fluidThermo().mu(), Urelative)
          + this->divDevTauCorr
            (
              - fvc::interpolate(continuousPhase().fluidThermo().mu())
               *fvc::dotInterpolate(this->mesh().Sf(), dev2(T(fvc::grad(U)))),
                U
            )
          + fvc::div
            (
                continuousPhase().fluidThermo().mu()
               *dev2(T(fvc::grad(Urelative)))
            )
        );

    tmp<fvVectorMatrix> divDevTauTurb =
      - fvm::laplacian(this->alpha_*this->rho_*nuTurbScaled_, U)
      + fvc::laplacian(this->alpha_*this->rho_*nuTurbScaled_, Urelative)
      + this->divDevTauCorr
        (
          - fvc::interpolate(this->alpha_*this->rho_*nuTurbScaled_)
           *fvc::dotInterpolate(this->mesh().Sf(), dev2(T(fvc::grad(U)))),
            U
        )
      + fvc::div
        (
            (this->alpha_*this->rho_*nuTurbScaled_)
           *dev2(T(fvc::grad(Urelative)))
        )
      + fvc::div
        (
            this->alpha_*this->rho()*scalingFactor_
           *2.0/3.0*I*continuousTurbulence().k()
        );

    return divDevTauVisc + divDevTauTurb;
}


void Foam::RASModels::disperseGasZeroEquation::correct()
{
    const phaseSystem& fluid = phase_.fluid();
    const dispersedPhaseInterface interface(phase_, continuousPhase());

    const dragModels::dispersedDragModel& drag  =
        fluid.lookupInterfacialModel<dragModels::dispersedDragModel>(interface);
    const virtualMassModels::dispersedVirtualMassModel& vm =
        fluid.lookupInterfacialModel
        <virtualMassModels::dispersedVirtualMassModel>
        (
            interface
        );

    const volScalarField St
    (
        particleCrossTimeScale_
      ? interface.St(CT_, CLambda_)
      : (this->rho() + continuousPhase().rho()*vm.Cvm())/drag.Ki()
       *continuousTurbulence().epsilon()/(CT_*continuousTurbulence().k())
    );

    scalingFactor_ = 1.0/(1.0 + St);

    nuTurbScaled_ = scalingFactor_*continuousTurbulence().nut();
}


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