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

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

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

        addToRunTimeSelectionTable
        (
            fvModel,
            filmEulerTransfer,
            dictionary
        );
    }
}


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

Foam::fv::filmEulerTransfer::filmEulerTransfer
(
    const word& sourceName,
    const word& modelType,
    const fvMesh& mesh,
    const dictionary& dict
)
:
    fvModel(sourceName, modelType, mesh, dict),
    film_(mesh.lookupObject<solvers::isothermalFilm>(solver::typeName)),
    curTimeIndex_(-1),
    morphologyTransferDict_(),
    transferRate_
    (
        volScalarField::Internal::New
        (
            "transferRate",
            mesh,
            dimensionedScalar(dimless/dimTime, 0)
        )
    )
{
    if (dict.found("morphologyTransfer"))
    {
        morphologyTransferDict_ = dict.subDict("morphologyTransfer");
    }
}


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

Foam::wordList Foam::fv::filmEulerTransfer::addSupFields() const
{
    return wordList
    {
        film_.alpha.name(),
        film_.thermo.he().name(),
        film_.U.name()
    };
}


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

    curTimeIndex_ = mesh().time().timeIndex();

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


    // Film properties

    const labelList& faceCells = film_.surfacePatch().faceCells();
    const scalarField& delta = film_.delta();


    // Euler properties

    const solvers::multiphaseEuler& Euler_
    (
        film_.surfacePatchMap().nbrMesh().lookupObject
        <
            solvers::multiphaseEuler
        >
        (
            solver::typeName
        )
    );

    const label patchiEuler = film_.surfacePatchMap().nbrFvPatch().index();

    const EulerFilmTransfer& EulerFilm(this->EulerFilm(Euler_.fvModels()));

    const scalarField alphaEuler
    (
        film_.surfacePatchMap().fromNeighbour
        (
            EulerFilm.alpha().boundaryField()[patchiEuler]
        )
    );

    const scalarField deltaCoeffsEuler
    (
        film_.surfacePatchMap().fromNeighbour
        (
            Euler_.mesh.boundary()[patchiEuler].deltaCoeffs()
        )
    );

    const scalarField deltaEuler
    (
        film_.surfacePatchMap().fromNeighbour
        (
            EulerFilm.filmThickness()
                      .ref()
                      .boundaryField()[patchiEuler]
        )
    );

    const scalarField totalDelta(delta + deltaEuler);

    // Reset the transfer rate
    transferRate_ = Zero;

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

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

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

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

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

        const volScalarField& VbyAs = film_.VbyA;

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

            if
            (
                delta[celli] > 2*deltaFactorToEuler/deltaCoeffsEuler[facei]
             || alphaEuler[facei] > alphaToEuler
             || (
                    totalDelta[facei] > totalDeltaToEuler
                 && delta[celli] > 0
                )
            )
            {
                transferRate_[celli] =
                    min
                    (
                        sqrt(mag(delta[facei]/VbyAs[facei]))/timeScale,
                        0.5*mag(delta[facei]/VbyAs[facei])/deltaT
                    );
            }
        }
    }

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


const Foam::fv::EulerFilmTransfer& Foam::fv::filmEulerTransfer::EulerFilm
(
    const Foam::fvModels& fvModels
) const
{
    const EulerFilmTransfer* EulerFilmPtr = nullptr;

    forAll(fvModels, i)
    {
        if (isType<EulerFilmTransfer>(fvModels[i]))
        {
            const EulerFilmTransfer& EulerFilm
            (
                refCast<const EulerFilmTransfer>(fvModels[i])
            );

            if
            (
                EulerFilm.filmPatchIndex()
             == film_.surfacePatchMap().nbrFvPatch().index()
            )
            {
                EulerFilmPtr = &EulerFilm;
            }
        }
    }

    if (!EulerFilmPtr)
    {
        FatalErrorInFunction
            << "Cannot find EulerFilmTransfer fvModel for this film "
               "in Euler region " << film_.surfacePatchMap().nbrMesh().name()
            << exit(FatalError);
    }

    return *EulerFilmPtr;
}


template<class Type, class TransferRateFunc>
Foam::tmp<Foam::VolInternalField<Type>>
inline Foam::fv::filmEulerTransfer::EulerToFilmTransferRate
(
    TransferRateFunc transferRateFunc,
    const dimensionSet& dimProp
) const
{
    const Foam::fvModels& fvModels =
        fvModels::New(film_.surfacePatchMap().nbrMesh());

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

    UIndirectList<Type>(tSu.ref(), film_.surfacePatch().faceCells()) =
        film_.surfacePatchMap().fromNeighbour
        (
            (EulerFilm(fvModels).*transferRateFunc)()
        );

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


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

    if (&alpha == &film_.alpha)
    {
        // Explicit transfer into the film
        eqn +=
            EulerToFilmTransferRate<scalar>
            (
                &EulerFilmTransfer::rhoTransferRate,
                dimMass
            );

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


void Foam::fv::filmEulerTransfer::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 == &film_.thermo.he())
    {
        // Explicit transfer into the film
        eqn +=
            EulerToFilmTransferRate<scalar>
            (
                &EulerFilmTransfer::heTransferRate,
                dimEnergy
            );

        // Potentially implicit transfer out of the film
        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::filmEulerTransfer::addSup
(
    const volScalarField& alpha,
    const volScalarField& rho,
    const volVectorField& U,
    fvMatrix<vector>& eqn
) const
{
    if (debug)
    {
        Info<< type() << ": applying source to " << eqn.psi().name() << endl;
    }

    if (&U == &film_.U)
    {
        // Explicit transfer into the film
        eqn +=
            EulerToFilmTransferRate<vector>
            (
                &EulerFilmTransfer::UTransferRate,
                dimMomentum
            );

        // Potentially implicit transfer out of the film
        if (&U == &eqn.psi())
        {
            eqn -= fvm::Sp(alpha()*rho()*transferRate_, eqn.psi());
        }
        else
        {
            eqn -= alpha()*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::filmEulerTransfer::TransferRate
(
    const FieldType& f
) const
{
    const labelList& faceCells = film_.surfacePatch().faceCells();

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


Foam::tmp<Foam::scalarField>
Foam::fv::filmEulerTransfer::transferRate() const
{
    return TransferRate<scalar>(oneField());
}


Foam::tmp<Foam::scalarField>
Foam::fv::filmEulerTransfer::rhoTransferRate() const
{
    return TransferRate<scalar>(film_.thermo.rho()());
}


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


Foam::tmp<Foam::vectorField>
Foam::fv::filmEulerTransfer::UTransferRate() const
{
    return TransferRate<vector>(film_.thermo.rho()()*film_.U());
}


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


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


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


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


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