/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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 "graphicalResiduals.H"
#include "Time.H"
#include "fvMesh.H"
#include "addToRunTimeSelectionTable.H"
#include "Residuals.H"

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

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


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

Foam::functionObjects::graphicalResiduals::graphicalResiduals
(
    const word& name,
    const Time& runTime,
    const dictionary& dict
)
:
    fvMeshFunctionObject(name, runTime, dict),
    app_(),
    endTime_(runTime.endTime().value()),
    fieldNames_(wordList::null()),
    seriesNames_(wordList::null())
{
    read(dict);

    if (Pstream::master())
    {
        forAll(fieldNames_, fieldi)
        {
            word& fieldName = fieldNames_[fieldi];
            seriesNames<scalar>(fieldName);
            seriesNames<vector>(fieldName);
            seriesNames<sphericalTensor>(fieldName);
            seriesNames<symmTensor>(fieldName);
            seriesNames<tensor>(fieldName);
        }

        // Build argv and argc for QApplication
        char* windowName = new char[runTime.caseName().length() + 1];
        strcpy(windowName, runTime.caseName().c_str());
        char* argv[] = { windowName, nullptr };
        int   argc   = 1;

        app_ = new QApplication(argc, argv);
        window_ = new window(seriesNames_);
        window_->setTimeRange(time_.startTime().value(), endTime_);

        app_->processEvents();
    }
}


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

Foam::functionObjects::graphicalResiduals::~graphicalResiduals()
{
    if (Pstream::master())
    {
        app_->closeAllWindows();
        delete window_;
        delete app_;
    }
}


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

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

    if (fieldNames_.empty() || dict.found("fields"))
    {
        dict.lookup("fields") >> fieldNames_;
    }

    return true;
}


Foam::wordList Foam::functionObjects::graphicalResiduals::fields() const
{
    return fieldNames_;
}


bool Foam::functionObjects::graphicalResiduals::execute()
{
    if (Pstream::master())
    {
        scalar sTime = time_.startTime().value();
        scalar eTime = time_.endTime().value();
        scalar rTime = time_.value();
        scalar cpuTime = time_.elapsedClockTime();

        label estimatedTime = floor(cpuTime*(eTime - rTime)/(rTime - sTime));
        label hour = 0;
        label min = 0;
        label sec = 0;

        hour = estimatedTime/3600;
        sec = estimatedTime%3600;
        min = sec/60;
        sec = sec%60;

        char str [30];
        sprintf(str, "%02d h %02d m %02d s", hour, min, sec);

        window_->setProgress(floor(rTime/eTime*100));
        window_->setEstimatedTime(str);

        if (endTime_ != eTime)
        {
            window_->setTimeRange(sTime, eTime);
            endTime_ = eTime;
        }

        forAll(fieldNames_, fieldi)
        {
            word& fieldName = fieldNames_[fieldi];
            printResidual<scalar>(fieldName);
            printResidual<vector>(fieldName);
            printResidual<sphericalTensor>(fieldName);
            printResidual<symmTensor>(fieldName);
            printResidual<tensor>(fieldName);
        }

        app_->processEvents();
    }

    return true;
}


bool Foam::functionObjects::graphicalResiduals::end()
{
    return true;
}


bool Foam::functionObjects::graphicalResiduals::write()
{
    return true;
}


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