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

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

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


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

void Foam::fv::degassingPhases::readCoeffs(const dictionary& dict)
{
}


bool Foam::fv::degassingPhases::isDegassingPhase(const word& fieldName) const
{
    return pos0(findIndex(degassingPhases_, IOobject::group(fieldName)));
}


template<class Type>
void Foam::fv::degassingPhases::addSupType
(
    const volScalarField& alpha,
    const volScalarField& rho,
    const VolField<Type>& field,
    fvMatrix<Type>& eqn
) const
{
    const scalar rDeltaT = 1.0/mesh().time().deltaT().value();

    volScalarField::Internal Sp
    (
        IOobject
        (
            name() + ":" + field.name() + ":Sp",
            mesh().time().name(),
            mesh()
        ),
        mesh(),
        dimensionedScalar(dimDensity/dimTime, Zero),
        false
    );

    const labelList& cells = zone_.zone();

    forAll(cells, i)
    {
        Sp[cells[i]] -= rho[cells[i]]*alpha[cells[i]]*rDeltaT;
    }

    eqn += fvm::SuSp(Sp, eqn.psi());
}


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

Foam::fv::degassingPhases::degassingPhases
(
    const word& name,
    const word& modelType,
    const fvMesh& mesh,
    const dictionary& dict
)
:
    fvModel(name, modelType, mesh, dict),
    degassingPhases_(dict.lookup<wordList>("degassingPhases")),
    continuousPhase_(dict.lookupOrDefault<word>("continuousPhase", "default")),
    alphaName_(dict.lookupOrDefault<word>("alphaName", "alpha")),
    fluid_(mesh.lookupObject<phaseSystem>(phaseSystem::propertiesName)),
    zone_(mesh, coeffs(dict))
{
    read(dict);

    if (continuousPhase_ == "default")
    {
        const phaseSystem::phaseModelPartialList& continuousPhases =
            fluid_.resolvedInterface().continuousPhases();

        if (continuousPhases.size() == 1)
        {
            fieldNames_.append(continuousPhases[0].rho()().name());

            continuousPhase_ = continuousPhases[0].name();
        }
        else
        {
            FatalIOErrorInFunction(dict)
                << "Exactly one continuous phase is required, but there are "
                << fluid_.resolvedInterface().continuousPhases().size()
                << " specified."
                << endl << exit(FatalIOError);
        }
    }
    else
    {
        const phaseModel& phase = fluid_.phases()[continuousPhase_];
        fieldNames_.append(phase.rho()().name());
    }

    // List of solution variables to apply correction sink term to
    const wordList solutionVariables
    (
        wordList{"U", "k", "R", "epsilon", "omega"}
    );

    forAll(degassingPhases_, phasei)
    {
        const phaseModel& phase = fluid_.phases()[degassingPhases_[phasei]];

        // Add phase density field
        fieldNames_.append(phase.rho()().name());

        // Add fields of solution variables
        forAll(solutionVariables, variablei)
        {
            const word variable = solutionVariables[variablei];
            const word fieldName =
                IOobject::groupName(variable, phase.name());

            if (pos0(findIndex(mesh.toc(), fieldName)))
            {
                fieldNames_.append(fieldName);
            }
        }

        // Add field of solution variable for energy
        if (!phase.isothermal())
        {
            fieldNames_.append(phase.thermo().he().name());
        }

        // Add size group fields
        if (isA<diameterModels::populationBalance>(phase.diameter()))
        {
            const diameterModels::populationBalance& popBalDiameterModel =
                refCast<const diameterModels::populationBalance>
                (
                    phase.diameter()
                );

            for
            (
                label i = popBalDiameterModel.iFirst();
                i <= popBalDiameterModel.iLast();
                i++
            )
            {
                fieldNames_.append(popBalDiameterModel.popBal().f(i).name());
            }
        }
    }

    if (debug)
    {
        word phases = degassingPhases_[0];
        for (Foam::label i=1; i<degassingPhases_.size(); i++)
        {
            phases += ", " + degassingPhases_[i];
        }
        Info<< "    Degassing phases: " << phases << nl
            << "    Continuous phase: " << continuousPhase_ << endl;
    }
}


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

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


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

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


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


void Foam::fv::degassingPhases::addSup
(
    const volScalarField& alpha,
    const volScalarField& field,
    fvMatrix<scalar>& eqn
) const
{
    const scalar rDeltaT = 1.0/mesh().time().deltaT().value();

    volScalarField::Internal Sp
    (
        IOobject
        (
            name() + ":" + field.name() + ":Sp",
            mesh().time().name(),
            mesh()
        ),
        mesh(),
        dimensionedScalar(dimless/dimTime, Zero),
        false
    );

    if (isDegassingPhase(field.name()))
    {
        const labelList& cells = zone_.zone();

        forAll(cells, i)
        {
            Sp[cells[i]] -= alpha[cells[i]]*rDeltaT;
        }
    }
    else
    {
        scalar volumeRate = 0.0;
        scalar boundaryRate = 0.0;

        forAll(degassingPhases_, namei)
        {
            const surfaceScalarField& phi =
                mesh().lookupObject<surfaceScalarField>
                (
                    IOobject::groupName("phi", degassingPhases_[namei])
                );

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

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

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

                boundaryRate +=
                    sum
                    (
                       phi.boundaryField()[patchi]
                      *degassingAlpha.boundaryField()[patchi]
                    );
            }

            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(degassingAlpha, rhoAlpha) & rhoAlpha
                    );

                    volumeRate -= sum(source*mesh().cellVolumes()/rhoAlpha);
                }
            }
        }

        reduce(boundaryRate, sumOp<scalar>());
        reduce(volumeRate, sumOp<scalar>());

        scalar rate = (volumeRate + boundaryRate)/zone_.V();

        DebugInfo << name() << ": " << field.name() << ": rate: " << rate
            << endl;

        const labelList& cells = zone_.zone();

        forAll(cells, i)
        {
            Sp[cells[i]] = rate;

            forAll(degassingPhases_, namei)
            {
                const volScalarField& degassingAlpha =
                    mesh().lookupObject<volScalarField>
                    (
                        IOobject::groupName
                        (
                            alphaName_, degassingPhases_[namei])
                    );

                Sp[cells[i]] += degassingAlpha[cells[i]]*rDeltaT;
            }
        }
    }

    DebugInfo<< name() << ": " << field.name() << ": Sp min, max: "
        << min(Sp).value() << ", " << max(Sp).value() << endl;

    if (debug && mesh().time().writeTime()) Sp.write();

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


FOR_ALL_FIELD_TYPES
(
    IMPLEMENT_FV_MODEL_ADD_ALPHA_RHO_FIELD_SUP,
    fv::degassingPhases
)


bool Foam::fv::degassingPhases::movePoints()
{
    zone_.movePoints();
    return true;
}


void Foam::fv::degassingPhases::topoChange(const polyTopoChangeMap& map)
{
    zone_.topoChange(map);
}


void Foam::fv::degassingPhases::mapMesh(const polyMeshMap& map)
{
    zone_.mapMesh(map);
}


void Foam::fv::degassingPhases::distribute
(
    const polyDistributionMap& map
)
{
    zone_.distribute(map);
}


bool Foam::fv::degassingPhases::read(const dictionary& dict)
{
    if (fvModel::read(dict))
    {
        zone_.read(coeffs(dict));
        readCoeffs(coeffs(dict));
        return true;
    }
    else
    {
        return false;
    }
}


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