/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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 "omegaMenterWallFunctionFvPatchScalarField.H"
#include "nutWallFunctionFvPatchScalarField.H"
#include "momentumTransportModel.H"
#include "fvMatrix.H"
#include "addToRunTimeSelectionTable.H"

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

Foam::Pair<Foam::tmp<Foam::scalarField>>
Foam::omegaMenterWallFunctionFvPatchScalarField::calculate
(
    const momentumTransportModel& mtm
) const
{
    const label patchi = patch().index();

    const nutWallFunctionFvPatchScalarField& nutw =
        nutWallFunctionFvPatchScalarField::nutw(mtm, patchi);

    const scalarField& y = mtm.yb()[patchi];

    const tmp<scalarField> tnuw = mtm.nu(patchi);
    const scalarField& nuw = tnuw();

    const tmp<volScalarField> tk = mtm.k();
    const volScalarField& k = tk();

    const fvPatchVectorField& Uw = mtm.U().boundaryField()[patchi];

    const scalarField magUp(mag(Uw.patchInternalField() - Uw));

    const scalar Cmu25 = pow025(nutw.Cmu());

    // Initialise the returned field pair
    Pair<tmp<scalarField>> GandOmega
    (
        tmp<scalarField>(new scalarField(patch().size())),
        tmp<scalarField>(new scalarField(patch().size()))
    );
    scalarField& G = GandOmega.first().ref();
    scalarField& omega = GandOmega.second().ref();

    // Calculate G and omega
    forAll(nutw, facei)
    {
        const label celli = patch().faceCells()[facei];

        const scalar Rey = y[facei]*sqrt(k[celli])/nuw[facei];
        const scalar yStar = Cmu25*Rey;

        const scalar omegaVis = 6*nuw[facei]/(beta1_*sqr(y[facei]));
        const scalar omegaLog = sqrt(k[celli])/(Cmu25*nutw.kappa()*y[facei]);

        const scalar uTauVis2 = nuw[facei]*magUp[facei]/y[facei];

        scalar uTauLog = 0.0;
        if (yStar > scalar(1.0))
        {
            uTauLog = nutw.kappa()*magUp[facei]/log(yStar*nutw.E());
        }

        const scalar uStarLog = Cmu25*sqrt(k[celli]);

        const scalar uTau = pow025(sqr(uTauVis2) + pow4(uTauLog));
        const scalar uStar = pow025(sqr(uTauVis2) + pow4(uStarLog));

        const scalar uPlus =
            inv(pow025
            (
                pow4(inv(yStar + vSmall))
              + pow4(nutw.kappa()*inv(log(nutw.E()*max(yStar, scalar(1.0)))))
            ));

        const scalar gradUplus =
            pow5(uPlus/(yStar + vSmall))
          + pow5
            (
                uPlus*nutw.kappa()*inv(log(nutw.E()*max(yStar, scalar(1.0))))
            )
           /(nutw.kappa()*(yStar + vSmall));

        G[facei] = sqr(uTau*uStar)/nuw[facei]*(1 - gradUplus)*gradUplus;

        omega[facei] = sqrt(sqr(omegaVis) + sqr(omegaLog));
    }

    return GandOmega;
}


void Foam::omegaMenterWallFunctionFvPatchScalarField::updateCoeffsMaster()
{
    if (patch().index() != masterPatchIndex())
    {
        return;
    }

    // Lookup the momentum transport model
    const momentumTransportModel& mtm =
        db().lookupType<momentumTransportModel>(internalField().group());

    // Get mutable references to the turbulence fields
    VolInternalField<scalar>& G =
        db().lookupObjectRef<VolInternalField<scalar>>(mtm.GName());
    volScalarField& omega =
        const_cast<volScalarField&>
        (
            static_cast<const volScalarField&>
            (
                internalField()
            )
        );

    const volScalarField::Boundary& omegaBf = omega.boundaryField();

    // Make all processors build the near wall distances
    mtm.yb();

    // Evaluate all the wall functions
    PtrList<scalarField> Gpfs(omegaBf.size());
    PtrList<scalarField> omegaPfs(omegaBf.size());
    forAll(omegaBf, patchi)
    {
        if (isA<omegaMenterWallFunctionFvPatchScalarField>(omegaBf[patchi]))
        {
            const omegaMenterWallFunctionFvPatchScalarField& omegaPf =
                refCast<const omegaMenterWallFunctionFvPatchScalarField>
                (omegaBf[patchi]);

            Pair<tmp<scalarField>> GandOmega = omegaPf.calculate(mtm);

            Gpfs.set(patchi, GandOmega.first().ptr());
            omegaPfs.set(patchi, GandOmega.second().ptr());
        }
    }

    // Average the values into the wall-adjacent cells and store
    wallCellGPtr_.reset(patchFieldsToWallCellField(Gpfs).ptr());
    wallCellOmegaPtr_.reset(patchFieldsToWallCellField(omegaPfs).ptr());

    // Set the fractional proportion of the value in the wall cells
    UIndirectList<scalar>(G, wallCells()) =
        (1 - wallCellFraction())*scalarField(G, wallCells())
      + wallCellFraction()*wallCellGPtr_();
    UIndirectList<scalar>(omega, wallCells()) =
        (1 - wallCellFraction())*scalarField(omega, wallCells())
      + wallCellFraction()*wallCellOmegaPtr_();
}


void Foam::omegaMenterWallFunctionFvPatchScalarField::manipulateMatrixMaster
(
    fvMatrix<scalar>& matrix
)
{
    if (patch().index() != masterPatchIndex())
    {
        return;
    }

    matrix.setValues(wallCells(), wallCellOmegaPtr_(), wallCellFraction());
}


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

Foam::omegaMenterWallFunctionFvPatchScalarField::
omegaMenterWallFunctionFvPatchScalarField
(
    const fvPatch& p,
    const DimensionedField<scalar, volMesh>& iF,
    const dictionary& dict
)
:
    wallCellWallFunctionFvPatchScalarField(p, iF, dict),
    beta1_(dict.lookupOrDefault<scalar>("beta1", dimless, 0.075)),
    wallCellGPtr_(nullptr),
    wallCellOmegaPtr_(nullptr)
{}


Foam::omegaMenterWallFunctionFvPatchScalarField::
omegaMenterWallFunctionFvPatchScalarField
(
    const omegaMenterWallFunctionFvPatchScalarField& ptf,
    const fvPatch& p,
    const DimensionedField<scalar, volMesh>& iF,
    const fieldMapper& mapper
)
:
    wallCellWallFunctionFvPatchScalarField(ptf, p, iF, mapper),
    beta1_(ptf.beta1_),
    wallCellGPtr_(nullptr),
    wallCellOmegaPtr_(nullptr)
{}


Foam::omegaMenterWallFunctionFvPatchScalarField::
omegaMenterWallFunctionFvPatchScalarField
(
    const omegaMenterWallFunctionFvPatchScalarField& owfpsf,
    const DimensionedField<scalar, volMesh>& iF
)
:
    wallCellWallFunctionFvPatchScalarField(owfpsf, iF),
    beta1_(owfpsf.beta1_),
    wallCellGPtr_(nullptr),
    wallCellOmegaPtr_(nullptr)
{}


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

void Foam::omegaMenterWallFunctionFvPatchScalarField::map
(
    const fvPatchScalarField& ptf,
    const fieldMapper& mapper
)
{
    wallCellWallFunctionFvPatchScalarField::map(ptf, mapper);
    wallCellGPtr_.clear();
    wallCellOmegaPtr_.clear();
}


void Foam::omegaMenterWallFunctionFvPatchScalarField::reset
(
    const fvPatchScalarField& ptf
)
{
    wallCellWallFunctionFvPatchScalarField::reset(ptf);
    wallCellGPtr_.clear();
    wallCellOmegaPtr_.clear();
}


void Foam::omegaMenterWallFunctionFvPatchScalarField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    initMaster();

    updateCoeffsMaster();

    operator==(patchInternalField());

    fvPatchField<scalar>::updateCoeffs();
}


void Foam::omegaMenterWallFunctionFvPatchScalarField::manipulateMatrix
(
    fvMatrix<scalar>& matrix
)
{
    if (manipulatedMatrix())
    {
        return;
    }

    if (masterPatchIndex() == -1)
    {
        FatalErrorInFunction
            << "updateCoeffs must be called before manipulateMatrix"
            << exit(FatalError);
    }

    manipulateMatrixMaster(matrix);

    fvPatchScalarField::manipulateMatrix(matrix);
}


void Foam::omegaMenterWallFunctionFvPatchScalarField::write(Ostream& os) const
{
    writeEntry(os, "beta1", beta1_);
    fixedValueFvPatchField<scalar>::write(os);
}


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

namespace Foam
{
    makePatchTypeField
    (
        fvPatchScalarField,
        omegaMenterWallFunctionFvPatchScalarField
    );
}


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