/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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 "dimensionlessNumbers.H"
#include "addToRunTimeSelectionTable.H"
#include "dispersedPhaseInterface.H"

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

namespace Foam
{
namespace functionObjects
{
    defineTypeNameAndDebug(dimensionlessNumbers, 0);
    addToRunTimeSelectionTable
    (
        functionObject,
        dimensionlessNumbers,
        dictionary
    );
}
}

const Foam::NamedEnum
<
    Foam::functionObjects::dimensionlessNumbers::fieldType,
    7
>
Foam::functionObjects::dimensionlessNumbers::fieldsNames_
{"Re", "Pr", "Eo", "Mo", "Ta", "St", "Sr"};


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

template<class Type>
void Foam::functionObjects::dimensionlessNumbers::processField
(
    const word& fieldName,
    const tmp<VolField<Type>>& tvalue
)
{
    typedef VolField<Type> FieldType;

    const word scopedName
    (
        IOobject::groupName
        (
            fieldName,
            dispersedPhase_.name() + "_dispersedIn_" + continuousPhase_.name()
        )
    );

    if (obr_.foundObject<FieldType>(scopedName))
    {
        obr_.lookupObjectRef<FieldType>(scopedName) == tvalue();
    }
    else if (obr_.found(scopedName))
    {
        WarningInFunction
            << "Cannot store " << scopedName
            << " since an object with that name already exists"
            << nl << endl;
    }
    else
    {
        obr_.store
        (
            new FieldType
            (
                IOobject
                (
                    scopedName,
                    obr_.time().name(),
                    obr_,
                    IOobject::READ_IF_PRESENT,
                    IOobject::NO_WRITE
                ),
                tvalue
            )
        );
    }
}


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

Foam::functionObjects::dimensionlessNumbers::dimensionlessNumbers
(
    const word& name,
    const Time& runTime,
    const dictionary& dict
)
:
    fvMeshFunctionObject(name, runTime, dict),
    dispersedPhase_
    (
        mesh_.lookupObject<phaseModel>
        (
            IOobject::groupName("alpha", dict.lookup("dispersedPhase"))
        )
    ),
    continuousPhase_
    (
        mesh_.lookupObject<phaseModel>
        (
            IOobject::groupName("alpha", dict.lookup("continuousPhase"))
        )
    ),
    fields_(),
    CT_(0.224),
    CLambda_(0.234),
    residualRe_(0.1),
    fluid_(mesh_.lookupObject<phaseSystem>("phaseProperties"))
{
    read(dict);
}


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

Foam::functionObjects::dimensionlessNumbers::~dimensionlessNumbers()
{}


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

bool Foam::functionObjects::dimensionlessNumbers::read(const dictionary& dict)
{
    fvMeshFunctionObject::read(dict);

    if (dispersedPhase_.name() == continuousPhase_.name())
    {
        FatalIOErrorInFunction(dict) << "Selected phases are identical"
                << exit(FatalIOError);
    }

    if (dict.found("field"))
    {
        fields_.insert(word(dict.lookup("field")));
    }
    else
    {
        fields_.insert(wordList(dict.lookup("fields")));
    }

    if (fields_.found("St"))
    {
        if (dict.found("St"))
        {
            CT_ = dimensionedScalar
            (
                "CT",
                dimless,
                dict.subDict("St").lookup("CT")
            );
            CLambda_ = dimensionedScalar
            (
                "CLambda",
                dimless,
                dict.subDict("St").lookup("CLambda")
            );
        }
    }

    if (fields_.found("Sr"))
    {
        if (dict.found("Sr"))
        {
            residualRe_ = dimensionedScalar
            (
                "residualRe",
                dimless,
                dict.subDict("Sr").lookup("residualRe")
            );
        }
    }

    Info<< type() << " " << name() << ": ";
    if (fields_.size())
    {
        Info<< "storing fields:" << nl;
        forAllConstIter(wordHashSet, fields_, iter)
        {
            Info<< "    "
                << IOobject::groupName
                (
                    iter.key(),
                    dispersedPhase_.name()
                  + "_dispersedIn_"
                  + continuousPhase_.name()
                )
                << nl;
        }
        Info<< endl;
    }
    else
    {
        Info<< "No fields requested to be stored." << nl << endl;
    }

    return true;
}


bool Foam::functionObjects::dimensionlessNumbers::execute()
{
    const dispersedPhaseInterface interface(dispersedPhase_, continuousPhase_);

    forAllConstIter(wordHashSet, fields_, iter)
    {
        const word& f = iter.key();
        switch (fieldsNames_[f])
        {
            case fieldType::Re:
            {
                processField<scalar>(f, interface.Re());
                break;
            }
            case fieldType::Pr:
            {
                processField<scalar>(f, interface.Pr());
                break;
            }
            case fieldType::Eo:
            {
                processField<scalar>(f, interface.Eo());
                break;
            }
            case fieldType::Mo:
            {
                processField<scalar>(f, interface.Mo());
                break;
            }
            case fieldType::Ta:
            {
                processField<scalar>(f, interface.Ta());
                break;
            }
            case fieldType::St:
            {
                processField<scalar>(f, interface.St(CT_, CLambda_));
                break;
            }
            case fieldType::Sr:
            {
                processField<scalar>
                (
                    f, interface.Sr(max(interface.Re(), residualRe_))
                );
                break;
            }
            default:
            {
                FatalErrorInFunction << "Invalid field selection"
                    << exit(FatalError);
            }
        }
    }

    return true;
}


bool Foam::functionObjects::dimensionlessNumbers::write()
{
    forAllConstIter(wordHashSet, fields_, iter)
    {
        const word fieldName
        (
            IOobject::groupName
            (
                iter.key(),
                dispersedPhase_.name()
              + "_dispersedIn_"
              + continuousPhase_.name()
            )
        );
        writeObject(fieldName);
    }

    return true;
}


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