/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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 "phaseMassController.H"
#include "fvMatrix.H"
#include "fvmSup.H"
#include "surfaceInterpolate.H"
#include "addToRunTimeSelectionTable.H"
#include "nonConformalCyclicFvPatchFields.H"

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

namespace Foam
{
namespace fv
{
    defineTypeNameAndDebug(phaseMassController, 0);
    addToRunTimeSelectionTable
    (
        fvModel,
        phaseMassController,
        dictionary
    );
}
}


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

bool
Foam::fv::phaseMassController::isControlledPhase(const word& fieldName) const
{
    return pos0(findIndex(controlledPhases_, IOobject::group(fieldName)));
}


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

Foam::fv::phaseMassController::phaseMassController
(
    const word& name,
    const word& modelType,
    const fvMesh& mesh,
    const dictionary& dict
)
:
    fvModel(name, modelType, mesh, dict),

    controlledPhases_(dict.lookup<wordList>("controlledPhases")),
    bufferPhase_(dict.lookup<word>("bufferPhase")),
    alphaName_("alpha"),
    fluid_(mesh.lookupObject<phaseSystem>(phaseSystem::propertiesName)),
    accountBoundaryFluxes_
    (
        dict.lookupOrDefault<Switch>("accountBoundaryFluxes", true)
    ),
    accountVolumeSources_
    (
        dict.lookupOrDefault<Switch>("accountVolumeSources", true)
    ),
    rate_(dimMass/dimTime, Zero),
    timeIndex0_(mesh.time().timeIndex()),
    MTarget_(dimMass, Zero),
    MTarget0_(dimMass, Zero)
{
    read(dict);

    Info<< "    - controlled phases:";
    forAll(controlledPhases_, phasei)
    {
        const phaseModel& phase = fluid_.phases()[controlledPhases_[phasei]];
        fieldNames_.append(phase.rho()().name());
        Info<< " " << phase.name();
    }
    Info<< endl;

    const phaseModel& phase = fluid_.phases()[bufferPhase_];
    fieldNames_.append(phase.rho()().name());
    Info<< "    - buffer phase: " << bufferPhase_ << endl;

    forAll(controlledPhases_, namei)
    {
        volScalarField& rhoAlpha =
            mesh().lookupObjectRef<volScalarField>
            (
                IOobject::groupName("rho", controlledPhases_[namei])
            );

        volScalarField& controlledAlpha =
            mesh().lookupObjectRef<volScalarField>
            (
                IOobject::groupName(alphaName_, controlledPhases_[namei])
            );

        MTarget_.value() += gSum(controlledAlpha*rhoAlpha*mesh.V());
    }
    MTarget0_ = MTarget_;
    Info<< "    - initial mass of controlled phases is "
        << MTarget_.value() << " kg" << endl;
}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::fv::phaseMassController::~phaseMassController()
{}


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

bool Foam::fv::phaseMassController::addsSupToField(const word& fieldName) const
{
    return pos0(findIndex(fieldNames_, fieldName));
}


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


void Foam::fv::phaseMassController::addSup
(
    const volScalarField& alpha,
    const volScalarField& field,
    fvMatrix<scalar>& eqn
) const
{
    volScalarField::Internal Sp
    (
        IOobject
        (
            name() + ":" + field.name() + ":Sp",
            mesh().time().name(),
            mesh()
        ),
        mesh(),
        dimensionedScalar(inv(dimTime), Zero),
        false
    );

    volScalarField::Internal sumControlledAlpha
    (
        IOobject
        (
            "sumControlledAlpha",
            mesh().time().name(),
            mesh()
        ),
        mesh(),
        dimensionedScalar(dimless, Zero)
    );

    volScalarField::Internal controlledRho
    (
        IOobject
        (
            "controlledRho",
            mesh().time().name(),
            mesh()
        ),
        mesh(),
        dimensionedScalar(dimDensity, Zero)
    );

    forAll(controlledPhases_, namei)
    {
        const volScalarField& rhoAlpha =
            mesh().lookupObject<volScalarField>
            (
                IOobject::groupName("rho", controlledPhases_[namei])
            );

        const volScalarField& controlledAlpha =
            mesh().lookupObject<volScalarField>
            (
                IOobject::groupName(alphaName_, controlledPhases_[namei])
            );

        sumControlledAlpha += controlledAlpha.internalField();
        controlledRho +=
            rhoAlpha.internalField()*controlledAlpha.internalField();
    }
    controlledRho /= max(sumControlledAlpha, dimensionedScalar(dimless, small));

    const volScalarField& bufferPhase =
        mesh().lookupObject<volScalarField>
        (
            IOobject::groupName(alphaName_, bufferPhase_)
        );

    volScalarField::Internal localSpecificRate
    (
        IOobject
        (
            "localSpecificRate",
            mesh().time().name(),
            mesh()
        ),
        mesh(),
        dimensionedScalar(dimDensity/dimTime, Zero)
    );

    localSpecificRate =
        rate_*bufferPhase.internalField()*sumControlledAlpha
       /dimensionedScalar
        (
            dimVolume,
            max
            (
                gSum
                (
                    (
                        bufferPhase.internalField()
                       *sumControlledAlpha*mesh().V()
                    ).ref()
                ),
                small
            )
        );

    if (isControlledPhase(field.name()))
    {
        const word phaseName(IOobject::group(field.name()));

        const volScalarField& rhoAlpha =
            mesh().lookupObject<volScalarField>
            (
                IOobject::groupName("rho", phaseName)
            );

        const volScalarField& controlledAlpha =
            mesh().lookupObject<volScalarField>
            (
                IOobject::groupName(alphaName_, phaseName)
            );

        Sp +=
            localSpecificRate/rhoAlpha*controlledAlpha
           /max(sumControlledAlpha, dimensionedScalar(dimless, small));
    }
    else if (field.name() == IOobject::groupName("rho", bufferPhase_))
    {
        Sp -=
            localSpecificRate
           /max(controlledRho, dimensionedScalar(dimDensity, small));
    }
    else
    {
        Info<< "Field is neither density field of controlled phase nor of "
            << "buffer phase: " << field.name() << endl;
    }

    // Distinguish between source and sourceProxy call
    if (&field == &eqn.psi())
    {
        eqn += fvm::SuSp(Sp, eqn.psi());
    }
    else
    {
        eqn += Sp*field;
    }
}


void Foam::fv::phaseMassController::correct()
{
    dimensionedScalar MActual(dimMass, Zero);

    // New time step
    if (mesh().time().timeIndex() > timeIndex0_)
    {
        MTarget0_ = MTarget_;
        timeIndex0_ = mesh().time().timeIndex();
    }

    dimensionedScalar MTarget(MTarget0_);

    forAll(controlledPhases_, namei)
    {
        const volScalarField& rhoAlpha =
            mesh().lookupObject<volScalarField>
            (
                IOobject::groupName("rho", controlledPhases_[namei])
            );

        const volScalarField& controlledAlpha =
            mesh().lookupObject<volScalarField>
            (
                IOobject::groupName(alphaName_, controlledPhases_[namei])
            );

        MActual.value() += gSum(controlledAlpha*rhoAlpha*mesh().V());

        if (accountBoundaryFluxes_)
        {
            const surfaceScalarField& alphaRhoPhi =
                mesh().lookupObject<surfaceScalarField>
                (
                    IOobject::groupName("alphaRhoPhi", controlledPhases_[namei])
                );

            forAll(mesh().boundary(), patchi)
            {
                if
                (
                    mesh().boundary()[patchi].coupled()
                 || isA<nonConformalCyclicFvPatch>(mesh().boundary()[patchi])
                )
                {
                    continue;
                }

                MTarget.value() -=
                    mesh().time().deltaTValue()
                   *gSum(alphaRhoPhi.boundaryField()[patchi]);
            }
        }

        if (accountVolumeSources_)
        {
            const fvModels& fvModels(fvModels::New(mesh()));
            const PtrListDictionary<fvModel>& modelList = fvModels;

            forAll(modelList, i)
            {
                const fvModel& model = modelList[i];

                if
                (
                    model.name() != this->name()
                 && model.addsSupToField(rhoAlpha.name())
                )
                {
                    const volScalarField source
                    (
                        model.source(controlledAlpha, rhoAlpha) & rhoAlpha
                    );

                    MTarget.value() +=
                        gSum(source*mesh().cellVolumes())
                       *mesh().time().deltaTValue();
                }
            }
        }
    }

    MTarget_ = MTarget;

    rate_ = -(MActual - MTarget)/mesh().time().deltaT();
}


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