/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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 "EulerFilmTransfer.H"
#include "filmEulerTransfer.H"
#include "mappedFvPatchBaseBase.H"
#include "fvmSup.H"
#include "addToRunTimeSelectionTable.H"
#include "addonFvcSpread.H"

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

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

        addToRunTimeSelectionTable
        (
            fvModel,
            EulerFilmTransfer,
            dictionary
        );
    }
}


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

Foam::fv::EulerFilmTransfer::EulerFilmTransfer
(
    const word& sourceName,
    const word& modelType,
    const fvMesh& mesh,
    const dictionary& dict
)
:
    fvModel(sourceName, modelType, mesh, dict),
    Euler_
    (
        mesh.lookupObject<solvers::multiphaseEuler>(solver::typeName)
    ),
    filmPatchName_(dict.lookup("filmPatch")),
    filmPatchi_
    (
        mesh.boundaryMesh().findIndex(filmPatchName_)
    ),
    phaseName_(dict.lookup("phase")),
    phase_
    (
        mesh.lookupObjectRef<phaseModel>
        (
            IOobject::groupName("alpha", phaseName_)
        )
    ),
    thermo_(phase_.fluidThermo()),
    curTimeIndex_(-1),
    morphologyTransferDict_
    (
        dict.found("morphologyTransfer")
      ? dict.subDict("morphologyTransfer")
      : dictionary()
    ),
    filmThicknessDict_(),
    transferRate_
    (
        volScalarField::Internal::New
        (
            "transferRate",
            mesh,
            dimensionedScalar(dimless/dimTime, 0)
        )
    )
{
    if (morphologyTransferDict_.found("filmThickness"))
    {
        filmThicknessDict_ = morphologyTransferDict_.subDict("filmThickness");
    }

    Info<< "Using " << typeName << " model" << endl;
}



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

Foam::wordList Foam::fv::EulerFilmTransfer::addSupFields() const
{
    return wordList
    {
        thermo_.rho()().name(),
        thermo_.he().name(),
        Euler_.phases[phaseName_].URef().name()
    };
}


void Foam::fv::EulerFilmTransfer::correct()
{
    if (curTimeIndex_ == mesh().time().timeIndex())
    {
        return;
    }

    curTimeIndex_ = mesh().time().timeIndex();
    const scalar deltaT = mesh().time().deltaTValue();

    const fvPatch& EulerFilmPatch = mesh().boundary()[filmPatchi_];

    const scalarField& deltaCoeffs = EulerFilmPatch.deltaCoeffs();

    const labelList& faceCells = EulerFilmPatch.faceCells();


    // Euler properties
    const scalarField& alpha = phase_.boundaryField()[filmPatchi_];

    // Film properties

    const mappedFvPatchBaseBase& EulerFilmPatchMap =
        refCast<const mappedFvPatchBaseBase>(EulerFilmPatch);

    const solvers::isothermalFilm& film_
    (
        EulerFilmPatchMap.nbrMesh().lookupObject<solvers::isothermalFilm>
        (
            solver::typeName
        )
    );

    const label filmEulerPatchi = EulerFilmPatchMap.nbrFvPatch().index();

    const scalarField delta
    (
        EulerFilmPatchMap.fromNeighbour
        (
            film_.delta.boundaryField()[filmEulerPatchi]
        )
    );

    scalar deltaMin = filmThicknessDict_.lookupOrDefault("deltaMin", -great);
    scalarField deltaEulerPatchValues(faceCells.size(), great);

    if (filmThicknessDict_.size())
    {
        if (debug)
        {
            Info<< "Calculating film thickness" << endl;
        }

        volScalarField deltaEuler(filmThickness());
        deltaEulerPatchValues = deltaEuler.boundaryField()[filmPatchi_];
    }

    // Morphology transfer
    transferRate_ = Zero;

    if (morphologyTransferDict_.size())
    {
        if (debug)
        {
            Info<< "Morphology transfer active" << endl;
        }

        const scalar timeScale
        (
            morphologyTransferDict_.lookup<scalar>("timeScale")
        );

        const scalar deltaFactorToFilm_
        (
            morphologyTransferDict_.lookupOrDefault<scalar>
            (
                "deltaFactorToFilm",
                great
            )
        );

        const scalar alphaToFilm_
        (
            morphologyTransferDict_.lookupOrDefault<scalar>
            (
                "alphaToFilm",
               -great
            )
        );

        forAll(faceCells, facei)
        {
            const label celli = faceCells[facei];

            if
            (
                alpha[facei] > 0
             && delta[facei] < 2*deltaFactorToFilm_/deltaCoeffs[facei]
             && (
                    alpha[facei] < alphaToFilm_
                 || deltaEulerPatchValues[facei] < deltaMin
                 || deltaEulerPatchValues[facei] < deltaMin
                )
            )
            {
                transferRate_[celli] =
                    min
                    (
                        sqrt(alpha[facei])/timeScale,
                        0.5*alpha[facei]/deltaT
                    );
            }
        }
    }

    if (debug)
    {
        if (mesh().time().writeTime())
        {
            volScalarField rateField
            (
                IOobject
                (
                    "rateEuler",
                    mesh().time().name(),
                    mesh(),
                    IOobject::NO_READ,
                    IOobject::NO_WRITE,
                    false
                ),
                mesh(),
                dimensionedScalar(dimless, Zero)
            );
            rateField.primitiveFieldRef() = transferRate_;
            rateField.write();
        }
    }
}

Foam::tmp<Foam::volScalarField>
Foam::fv::EulerFilmTransfer::filmThickness() const
{
    scalar nLayers = filmThicknessDict_.lookupOrDefault<label>("nLayers", 10);
    scalar yDiff = filmThicknessDict_.lookupOrDefault<scalar>("yDiff", -1);

    const word alphaFieldName = IOobject::groupName("alpha", phaseName_);

    if (!mesh().foundObject<volScalarField>(alphaFieldName))
    {
        FatalErrorInFunction << "Error: Field '" << alphaFieldName
            << "' not found in the mesh!" << exit(FatalError);
    }

    volScalarField alpha(mesh().lookupObject<volScalarField>(alphaFieldName));

    return fvc::integrateWallNormal
    (
        alpha,
        alpha,
        nLayers,
        filmPatchName_,
        yDiff
    );
}


template<class Type, class TransferRateFunc>
Foam::tmp<Foam::VolInternalField<Type>>
inline Foam::fv::EulerFilmTransfer::filmEulerTransferRate
(
    TransferRateFunc transferRateFunc,
    const dimensionSet& dimProp
) const
{
    const fvPatch& EulerFilmPatch = mesh().boundary()[filmPatchi_];

    const labelList& faceCells = EulerFilmPatch.faceCells();
    const mappedFvPatchBaseBase& EulerFilmPatchMap =
        refCast<const mappedFvPatchBaseBase>(EulerFilmPatch);

    const Foam::fvModels& fvModels =
        fvModels::New(EulerFilmPatchMap.nbrMesh());

    const filmEulerTransfer* filmEulerPtr = nullptr;

    forAll(fvModels, i)
    {
        if (isType<filmEulerTransfer>(fvModels[i]))
        {
            filmEulerPtr = &refCast<const filmEulerTransfer>(fvModels[i]);
        }
    }

    if (!filmEulerPtr)
    {
        FatalErrorInFunction
            << "Cannot find filmEulerTransfer fvModel for the film region "
            << EulerFilmPatchMap.nbrMesh().name()
            << exit(FatalError);
    }

    tmp<VolInternalField<Type>> tSu
    (
        VolInternalField<Type>::New
        (
            "Su",
            mesh(),
            dimensioned<Type>(dimProp/dimTime, Zero)
        )
    );

    UIndirectList<Type>(tSu.ref(), faceCells) =
        EulerFilmPatchMap.fromNeighbour
        (
            (filmEulerPtr->*transferRateFunc)()
        );

    return tSu/mesh().V();
}


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

    if (&rho == &thermo_.rho()())
    {
        // Explicit transfer into the Euler
        eqn +=
            filmEulerTransferRate<scalar>
            (
                &filmEulerTransfer::rhoTransferRate,
                dimMass
            );

        // Potentially implicit transfer out of the Euler
        if (&rho == &eqn.psi())
        {
            eqn -= fvm::Sp(alpha()*transferRate_, eqn.psi());
        }
        else if (&alpha == &eqn.psi())
        {
            eqn -= fvm::Sp(rho()*transferRate_, eqn.psi());
        }
        else
        {
            eqn -= alpha()*rho()*transferRate_;
        }
    }
    else
    {
        FatalErrorInFunction
            << "Support for field " << rho.name() << " is not implemented"
            << exit(FatalError);
    }
}


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

    if (&he == &thermo_.he())
    {
        // Explicit transfer into the Euler
        eqn +=
            filmEulerTransferRate<scalar>
            (
                &filmEulerTransfer::heTransferRate,
                dimEnergy
            );

        // Potentially implicit transfer out of the Euler
        if (&he == &eqn.psi())
        {
            eqn -= fvm::Sp(alpha()*rho()*transferRate_, eqn.psi());
        }
        else
        {
            eqn -= alpha()*rho()*he*transferRate_;
        }
    }
    else
    {
        FatalErrorInFunction
            << "Support for field " << he.name() << " is not implemented"
            << exit(FatalError);
    }
}


void Foam::fv::EulerFilmTransfer::addSup
(
    const volScalarField& rho,
    const volVectorField& U,
    fvMatrix<vector>& eqn
) const
{
    if (debug)
    {
        Info<< type() << ": applying source to " << eqn.psi().name() << endl;
    }

    if (&U == &Euler_.phases[phaseName_].URef())
    {
        // Explicit transfer into the Euler
        eqn +=
            filmEulerTransferRate<vector>
            (
                &filmEulerTransfer::UTransferRate,
                dimMass*dimVelocity
            );

        // Potentially implicit transfer out of the Euler
        if (&U == &eqn.psi())
        {
            eqn -= fvm::Sp(phase_()*rho()*transferRate_, eqn.psi());
        }
        else
        {
            eqn -= phase_()*rho()*U*transferRate_;
        }
    }
    else
    {
        FatalErrorInFunction
            << "Support for field " << U.name() << " is not implemented"
            << exit(FatalError);
    }
}


template<class Type, class FieldType>
inline Foam::tmp<Foam::Field<Type>> Foam::fv::EulerFilmTransfer::TransferRate
(
    const FieldType& f
) const
{
    const fvPatch& EulerFilmPatch = mesh().boundary()[filmPatchi_];

    const labelList& faceCells = EulerFilmPatch.faceCells();


    return tmp<Field<Type>>
    (
        new Field<Type>
        (
            UIndirectList<Type>
            (
                phase_()*transferRate_*mesh().V()*f,
                faceCells
            )
        )
    );
}


Foam::tmp<Foam::scalarField>
Foam::fv::EulerFilmTransfer::rhoTransferRate() const
{
    return TransferRate<scalar>(thermo_.rho()());
}


Foam::tmp<Foam::scalarField>
Foam::fv::EulerFilmTransfer::heTransferRate() const
{
    return TransferRate<scalar>(thermo_.rho()()*thermo_.he()());
}


Foam::tmp<Foam::vectorField>
Foam::fv::EulerFilmTransfer::UTransferRate() const
{
    return TransferRate<vector>
    (
        thermo_.rho()()*Euler_.phases[phaseName_].URef()()
    );
}


void Foam::fv::EulerFilmTransfer::topoChange(const polyTopoChangeMap&)
{
    transferRate_.setSize(mesh().nCells());
}


void Foam::fv::EulerFilmTransfer::mapMesh(const polyMeshMap& map)
{
    transferRate_.setSize(mesh().nCells());
}


void Foam::fv::EulerFilmTransfer::distribute(const polyDistributionMap&)
{
    transferRate_.setSize(mesh().nCells());
}


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


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