/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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

    Copyright (C) 2025 by Technische Universitaet Darmstadt,
    Website: https://www.tu-darmstadt.de

    Copyright (C) 2025 by Technische Universitaet Muenchen,
    Website: https://www.tum.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 "phaseStructureProperties.H"
#include "volFields.H"
#include "addToRunTimeSelectionTable.H"
#include "syncTools.H"
#include "surfaceFields.H"

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

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


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

Foam::tmp<Foam::scalarField>
Foam::functionObjects::phaseStructureProperties::interpolateCellDataToPointData
(
    const volScalarField & alpha
) const
{
    scalarField alphaP(mesh().nPoints(), Zero);
    scalarField sumP(mesh().nPoints(), Zero);

    // Interpolation of volume fraction from cells centres to the points
    // (could in general also be done by volPointInterpolate, however we
    // encountered some problems when using volPointInterpolate and
    // dynamicRefineFvMesh)
    forAll(zone_.zone(), cellI)
    {
        const cell faces(mesh().cells()[cellI]);
        forAll(faces, J)
        {
            const face points(mesh().faces()[faces[J]]);
            forAll(points, K)
            {
                const label pointK = points[K];

                const scalar d
                (
                    mag(mesh().C()[cellI] - mesh().points()[pointK])
                );
                alphaP[pointK] += alpha[cellI]/max(d, small);
                sumP[pointK] += inv(max(d, small));
            }
        }
    }

    // Synchronise values on selected mesh points.
    syncTools::syncPointList(mesh(), alphaP, plusEqOp<scalar>(), scalar(0.0));
    syncTools::syncPointList(mesh(), sumP, plusEqOp<scalar>(), scalar(0.0));

    return alphaP/max(sumP, small);
}


Foam::scalarField Foam::functionObjects::phaseStructureProperties::surfaceArea
(
    const scalarField& pField,
    const scalar crit
)
{
    scalarField SField(zone_.nCells(), Zero);
    scalarField cutContour(zone_.nCells(), Zero);

    forAll(zone_.zone(), cellI)
    {
        // Determine the number of faces which are cut by the interface and the
        // face which will be visited first during the reconstruction
        int startFace = -1;
        int cutFaces = 0;

        const cell faces = mesh().cells()[cellI];
        forAll(faces, j)
        {
            const label faceI = faces[j];

            face points = mesh().faces()[faceI];

            if (mesh().isInternalFace(faceI))
            {
                // Keep or reverse numbering of points such that the face vector
                // points out of the face (right hand rule)
                const label own = mesh().owner()[faceI];
                if (own != cellI)
                {
                    face pointsTmp(points.size());
                    pointsTmp = points;
                    for (int i = 0; i < points.size(); i++)
                    {
                        points[i] = pointsTmp[points.size()-1-i];
                    }
                }
            }

            // Check if face is cut by the interface
            bool cutFound = 0;
            int i = 0;
            while ((!cutFound) && (i < points.size()))
            {
                label ip1 = i+1;
                if (ip1 == points.size())
                {
                    ip1 = 0;
                }

                // Check if volume fraction change from below to above the
                // criterion along the edge between point xi and xip1
                const scalar di = pField[points[i]];
                const scalar dip1 = pField[points[ip1]];
                if
                (
                    ((di <= crit) && (dip1 >  crit))
                 || ((di <  crit) && (dip1 == crit))
                )
                {
                    cutFound = 1;

                    if (startFace == -1)
                    {
                        startFace = j;
                    }
                }
                i += 1;
            }

            if (cutFound)
            {
                cutFaces += 1;
            }
        }

        // Find corner points of the cutting polygon in right order
        // (start with startFace, see above)
        DynamicList<vector> xCuttingPlane;
        // contains the points of the cutting polygon; DynamicList since we
        // never know the actual number of cutting points a priori; one cutting
        // plane for every cell

        label nextFace = startFace;
        int N = 0;
        while (N < cutFaces)
        {
            label j = nextFace;
            label faceI = faces[j];
            face points = mesh().faces()[faceI];

            if (mesh().isInternalFace(faceI))
            {
                // Keep or reverse numbering of points such that the face vector
                // points out of the face (right hand rule); depends on the fact
                // if faces are internal or external faces
                label own = mesh().owner()[faceI];
                if (own != cellI)
                {
                    face pointsTmp(points.size());
                    pointsTmp = points;
                    for (int i = 0; i < points.size(); i++)
                    {
                        points[i] = pointsTmp[points.size()-1-i];
                    }
                }
            }

            // Loop over all mesh points of one face
            for (int i = 0; i < points.size(); i++)
            {
                label ip1 = i+1;

                //closed loop condition
                if (ip1 == points.size())
                {
                    ip1 = 0;
                }

                // Check, if volume fraction change from below to above
                // crit along the edge between point xi and xip1
                const vector xi = mesh().points()[points[i]];
                const vector xip1 = mesh().points()[points[ip1]];
                const scalar di = pField[points[i]];
                const scalar dip1 = pField[points[ip1]];

                if
                (
                    ((di <= crit) && (dip1 >  crit))
                 || ((di <  crit) && (dip1 == crit))
                ) //First possibility
                {
                    N += 1;

                    // Interpolate position along edge where volume fraction
                    // equals crit
                    const vector xNew = xi+(crit-di)/(dip1-di)*(xip1-xi);
                    bool exists = 0;

                    // Check if coordinate already exists in xCuttingPlane (can
                    // happen when volume fraction is exactly crit at one
                    // point of the cell)
                    for (int n = 0; n < xCuttingPlane.size(); n++)
                    {
                        if (xNew == xCuttingPlane[n])
                        {
                            exists = 1;
                            break;
                        }
                    }

                    // If coordinate does not yet exist, append it to
                    // xCuttingPlane
                    if (!exists)
                    {
                        xCuttingPlane.append(xNew);

                        if (cutContour[cellI] == 0)
                        {
                            cutContour[cellI] = 1;
                        }
                    }

                    bool found = 0;
                    int j2 = -1;

                    // Find the second face of the cell which shares the edge
                    // where we just obtained a new coordinate of the cutting
                    // polygon and make this the next face to visit (this
                    // ensures that the coordinates of the corner points are
                    // found according to the right hand rule) Loop over all
                    // faces of the cell OR until the face with sharing edge is
                    // found
                    while (!found)
                    {
                        j2 += 1;
                        label faceI2 = faces[j2];
                        face points2 = mesh().faces()[faceI2];

                        if (mesh().isInternalFace(faceI2))
                        {
                            label own2 = mesh().owner()[faceI2];
                            if (own2 != cellI)
                            {
                                face pointsTmp(points2.size());
                                pointsTmp = points2;
                                for (int i = 0; i < points2.size(); i++)
                                {
                                    points2[i] = pointsTmp[points2.size()-1-i];
                                }
                            }
                        }

                        for (int i2 = 0; i2 < points2.size(); i2++)
                        {
                            label i2p1 = i2+1;
                            if (i2p1 == points2.size())
                            {
                                i2p1 = 0;
                            }

                            if
                            (
                                (points2[i2] == points[ip1])
                             && (points2[i2p1] == points[i])
                            )
                            {
                                nextFace = j2;
                                found = 1;
                            }
                        }
                    }
                }
            }
        }

        // Calculate area vector
        if (cutContour[cellI])
        {
            vector SVec(Zero);

            for (int i = 0; i < xCuttingPlane.size(); i++)
            {
                label ip1 = i+1;
                //closed loop condition
                if (ip1 == xCuttingPlane.size())
                {
                    ip1 = 0;
                }
                const vector xi = xCuttingPlane[i];
                const vector xip1 = xCuttingPlane[ip1];
                SVec -= 0.5*(xi^xip1);
            }

            SField[cellI] = mag(SVec);
        }
    }

    return SField;
}

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

void Foam::functionObjects::phaseStructureProperties::writeFileHeader
(
    const label i
)
{
    zone_.writeFileHeader(*this, file());

    writeHeader
    (
        file(),
        "Centre of gravity, velocity, volume, surface area and sphericity "
        "for phase " + alphaName_
    );

    file()  <<"#"
        << setw(IOstream::defaultPrecision() + 7) << " Time"
        << setw(IOstream::defaultPrecision() + 8) << "X"
        << setw(IOstream::defaultPrecision() + 8) << "Y"
        << setw(IOstream::defaultPrecision() + 8) << "Z"
        << setw(IOstream::defaultPrecision() + 8) << "U"
        << setw(IOstream::defaultPrecision() + 8) << "V"
        << setw(IOstream::defaultPrecision() + 8) << "W"
        << setw(IOstream::defaultPrecision() + 8) << "Volume";
    if (calcSphericity_)
    {
        file()  << setw(IOstream::defaultPrecision() + 8) << "SurfaceArea"
            << setw(IOstream::defaultPrecision() + 8) << "Sphericity";
    }
    file()  << endl;
}


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

Foam::functionObjects::phaseStructureProperties::phaseStructureProperties
(
    const word& name,
    const Time& runTime,
    const dictionary& dict
)
:
    fvMeshFunctionObject(name, runTime, dict),
    logFiles(obr_, name),
    dict_(dict),
    zone_(fvMeshFunctionObject::mesh_, dict),
    thickness_(dimLength, 1),
    CG_(dimLength, Zero),
    velocity_(dimVelocity, Zero),
    volume_(dimVolume, Zero),
    area_(dimArea, Zero),
    sphericity_(dimless, Zero)
{
    read(dict);
    resetName(name);

    registerDimensionedObject("CG", CG_);
    registerDimensionedObject("velocity", velocity_);
    registerDimensionedObject("volume", volume_);
    if (calcSphericity_)
    {
        registerDimensionedObject("area", area_);
        registerDimensionedObject("sphericity", sphericity_);
    }

    if (mesh().nGeometricD() == 2)
    {
        twoDimensional_ = true;

        vector plane(0,0,0);
        if (mesh().geometricD().x() == -1)
        {
            plane = vector(1,0,0);
        }
        else if (mesh().geometricD().y() == -1)
        {
            plane = vector(0,1,0);
        }
        else if (mesh().geometricD().z() == -1)
        {
            plane = vector(0,0,1);
        }

        const cell& faces = mesh().cells()[0];
        const labelList points = faces.labels(mesh().faces());
        pointField pLocal(points.size(), vector::zero);
        forAll(points, i)
        {
            const label& pointI = points[i];
            pLocal[i] = mesh().points()[pointI];
        }

        thickness_.value() =
            Foam::max(pLocal & plane) - Foam::min(pLocal & plane);

        Info<< type() << ": "
            << "Calculating area (volume) and circularity (sphericity) "
            << "in 2D space" << nl
            << "plane " << plane << ", thickness " << thickness_ << nl << endl;
    }
    else if (mesh().nGeometricD() == 3)
    {
        twoDimensional_ = false;

        Info<< type() << ": Calculating volume and sphericity in 3D space."
            << nl << endl;
    }
    else
    {
        twoDimensional_ = false;

        WarningInFunction << type() << ": Only intended for 2D and 3D cases."
            << endl;
    }
}


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

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


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

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

    alphaName_ = dict.lookup<word>("alpha");
    velocityName_ = dict.lookupOrDefault<word>("U", "U");
    calcSphericity_ = dict.lookupOrDefault<Switch>("calcSphericity", true);
    threshold_ = dict.lookupOrDefault<scalar>("threshold", dimless, 0.5);

    return true;
}


bool Foam::functionObjects::phaseStructureProperties::execute()
{
    return true;
}


bool Foam::functionObjects::phaseStructureProperties::write()
{
    autoPtr<volScalarField> phasePtr;
    if (obr_.foundObject<volScalarField>(alphaName_))
    {
        Info<< "    Looking up field " << alphaName_ << endl;
    }
    else
    {
        Info<< "    Reading field " << alphaName_ << endl;
        phasePtr.reset
        (
            new volScalarField
            (
                IOobject
                (
                    alphaName_,
                    time_.name(),
                    obr_,
                    IOobject::MUST_READ,
                    IOobject::NO_WRITE
                ),
                fvMeshFunctionObject::mesh_
            )
        );
    }

    const volScalarField& alpha =
    (
         phasePtr.valid()
       ? phasePtr()
       : obr_.lookupObject<volScalarField>(alphaName_)
    );


    autoPtr<volVectorField> UPtr;
    if (obr_.foundObject<volVectorField>(velocityName_))
    {
        Info<< "    Looking up field " << velocityName_ << endl;
    }
    else
    {
        Info<< "    Reading field " << velocityName_ << endl;
        UPtr.reset
        (
            new volVectorField
            (
                IOobject
                (
                    velocityName_,
                    time_.name(),
                    obr_,
                    IOobject::MUST_READ,
                    IOobject::NO_WRITE
                ),
                fvMeshFunctionObject::mesh_
            )
        );
    }

    const volVectorField& U =
    (
         UPtr.valid()
       ? UPtr()
       : obr_.lookupObject<volVectorField>(velocityName_)
    );

    scalarField iPhase(filterField(alpha));
    scalarField iV(filterField(mesh().V()));
    vectorField iC(filterField(mesh().C()));
    vectorField iU(filterField(U));
    scalarField iA(zone_.nCells(), Zero);
    if (calcSphericity_)
    {
        iA =
            filterField
            (
                surfaceArea
                (
                    interpolateCellDataToPointData(alpha),
                    threshold_
                )
            );
    }

    // Combine onto master
    combineFields(iPhase);
    combineFields(iC);
    combineFields(iV);
    combineFields(iU);
    if (calcSphericity_)
    {
        combineFields(iA);
    }

    scalar phaseSum    = sum(scalarField(iPhase*iV));
    vector phaseByCSum = sum(vectorField(iPhase*iC*iV));
    vector phaseByUSum = sum(vectorField(iPhase*iU*iV));

    if (Pstream::master())
    {
        CG_.value() = phaseByCSum/max(phaseSum, small);
        velocity_.value() = phaseByUSum/max(phaseSum, small);
        volume_.value() = phaseSum/thickness_.value();

        if (calcSphericity_)
        {
            area_.value() = sum(iA)/thickness_.value();

            const scalar& pi(constant::mathematical::pi);
            if (twoDimensional_)
            {
                // volume_ translates to surface area and area_ translates to
                // perimeter
                const scalar dEquivalent(2*Foam::sqrt(volume_.value()/pi));
                sphericity_.value() = pi*dEquivalent/max(area_.value(), small);
            }
            else
            {
                const scalar dEquivalent(pow(6*volume_.value()/pi, 1.0/3.0));
                sphericity_.value() = pi*Foam::sqr(dEquivalent)
                   /max(area_.value(), small);
            }
        }
    }

    Pstream::scatter(CG_);
    Pstream::scatter(velocity_);
    Pstream::scatter(volume_);
    if (calcSphericity_)
    {
        Pstream::scatter(area_);
        Pstream::scatter(sphericity_);
    }

    registerDimensionedObject("CG", CG_);
    registerDimensionedObject("velocity", velocity_);
    registerDimensionedObject("volume", volume_);
    if (calcSphericity_)
    {
        registerDimensionedObject("area", area_);
        registerDimensionedObject("sphericity", sphericity_);
    }

    unsigned int w = IOstream::defaultPrecision() + 7;

    logFiles::write();

    if (Pstream::master())
    {
        file()  << setw(w) << time_.value();

        file()  << ' ' << setw(w) << CG_.value().x()
                << ' ' << setw(w) << CG_.value().y()
                << ' ' << setw(w) << CG_.value().z()
                << ' ' << setw(w) << velocity_.value().x()
                << ' ' << setw(w) << velocity_.value().y()
                << ' ' << setw(w) << velocity_.value().z()
                << ' ' << setw(w) << volume_.value();
        if (calcSphericity_)
        {
            file()  << ' ' << setw(w) << area_.value()
                    << ' ' << setw(w) << sphericity_.value();
        }
        file()  << endl;
    }

    Log << nl
        << "Properties of phase " << alphaName_ << ": " << nl
        << "    Centre of gravity: " << CG_.value() << nl
        << "    Velocity:          " << velocity_.value() << nl
        << "    Volume:            " << volume_.value() << nl;
    if (calcSphericity_)
    {
        Log << "    Surface area:      " << area_.value() << nl
            << "    Sphericity:        " << sphericity_.value() << nl;
    }
    Log << endl;

    return true;
}


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