/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     | faSavageHutterFOAM
    \\  /    A nd           | Copyright (C) 2017 Matthias Rauter
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM 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.

    OpenFOAM 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 OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

Author
    Matthias Rauter matthias.rauter@uibk.ac.at

\*---------------------------------------------------------------------------*/

#include "totalenergy.H"
#include "volFields.H"
#include "dictionary.H"
#include "foamTime.H"
#include "areaMesh.H"
#include "uniformDimensionedFields.H"
#include "cfdfunction.H"


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

namespace Foam
{
    defineTypeNameAndDebug(totalenergy, 0);
}

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



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

Foam::totalenergy::totalenergy
(
    const word& name,
    const objectRegistry& obr,
    const dictionary& dict,
    const bool loadFromFiles
):
    obr_(obr),
    loss_
    (
        IOobject
        (
            "loss",
            obr.lookupObject<areaVectorField>("Us").time().timeName(),
            obr.lookupObject<areaVectorField>("Us").db(),
            IOobject::NO_READ,
            IOobject::NO_WRITE
        ),
        obr.lookupObject<areaVectorField>("Us").mesh(),
        dimensionedScalar("zero", dimensionSet(1, 0, -2, 0, 0, 0, 0), 0)
    ),
    energyFilePtr_(NULL),
    rho_(dimensionedScalar("zero", dimensionSet(1, -3, 0, 0, 0, 0, 0), 0)),
    initialMass_(dimensionedScalar("zero", dimensionSet(1, 0, 0, 0, 0, 0, 0), 0)),
    minimalEnergy_(dimensionedScalar("zero", dimensionSet(1, 2, -2, 0, 0, 0, 0), 0))
{

    read(dict);


    const areaVectorField &Us = obr_.lookupObject<areaVectorField>("Us");
    const areaScalarField &h = obr_.lookupObject<areaScalarField>("h");

    const faMesh &aMesh = Us.mesh();

    const uniformDimensionedVectorField &g = obr_.lookupObject<uniformDimensionedVectorField>("g");

    initialMass_ = Foam::sum(aMesh.S()*h)*rho_;
    minimalEnergy_ = initialMass_*(Foam::min(g&aMesh.areaCentres())-Foam::max(g&aMesh.areaCentres()));


    Info << endl << "Analyzing mass and energy:" << endl
         << "   log is " << log_ << endl
         << "   inital mass = " << initialMass_.value() << endl
         << "   availible potential energy = " << -minimalEnergy_.value() << endl << endl;


}


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

Foam::totalenergy::~totalenergy()
{}


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

void Foam::totalenergy::read(const dictionary& dict)
{
    log_ = dict.lookupOrDefault<Switch>("log", false);
    rho_ = dimensionedScalar(dict.lookup("rho"));
    energyFilePtr_.reset(new OFstream(word(dict.lookup("tableOutPut"))));
    energyFilePtr_() << "time"        << tab
                     << "m_tot"       << tab
                     << "e_heat"      << tab
                     << "e_kin"       << tab
                     << "e_pot"       << tab
                     << "e_tot"       << endl;
}



void Foam::totalenergy::execute()
{
    const areaVectorField &Us = obr_.lookupObject<areaVectorField>("Us");
    const areaScalarField &h = obr_.lookupObject<areaScalarField>("h");
    const areaVectorField &tau = obr_.lookupObject<areaVectorField>("tau");
    const areaVectorField &pbn = obr_.lookupObject<areaVectorField>("pbn");
    const edgeScalarField &phis = obr_.lookupObject<edgeScalarField>("phis");

    areaScalarField &loss = loss_;

    const faMesh &aMesh = Us.mesh();
    const areaVectorField n = aMesh.faceAreaNormals();

    const uniformDimensionedVectorField &g = obr_.lookupObject<uniformDimensionedVectorField>("g");

    cfdfunction f(Us, h, tau, pbn, g, rho_, phis);
    f.calcLoss(loss);
    areaScalarField totalEnergy =
            loss
            -(aMesh.areaCentres()&g)*h*rho_
            +1/2.*h*h*(g&n)*rho_
            +1/2.*(Us&Us)*h*rho_;


    dimensionedScalar m_tot = Foam::sum(aMesh.S()*h)*rho_;
    dimensionedScalar e_heat = Foam::sum(aMesh.S()*loss);
    DimensionedField<scalar, areaMesh> hUsSqrRho(h*(Us&Us)*rho_);
    dimensionedScalar e_kin =  1/2.*Foam::sum(hUsSqrRho*aMesh.S());
    dimensionedScalar e_pot = -Foam::sum(DimensionedField<scalar, areaMesh>((aMesh.areaCentres()&g)*h*rho_)*aMesh.S())
            +1/2.*Foam::sum(DimensionedField<scalar, areaMesh>(h*h*(g&n)*rho_)*aMesh.S())
            -minimalEnergy_;
    dimensionedScalar e_tot = Foam::sum(aMesh.S()*totalEnergy)-minimalEnergy_;

    energyFilePtr_() << obr_.time().value() << tab
                     << m_tot.value()       << tab
                     << e_heat.value()      << tab
                     << e_kin.value()       << tab
                     << e_pot.value()       << tab
                     << e_tot.value()       << endl;
    if (log_)
    {
        Info << endl;
        Info << "Total mass = " << m_tot.value() << endl;
        Info << "Total heat energy = " << e_heat.value() << endl;
        Info << "Total kin energy = " <<  e_kin.value() << endl;
        Info << "Total pot energy = " << e_pot.value() << endl;
        Info << "Total energy = " << e_tot.value() << endl << endl;
    }
}


void Foam::totalenergy::end()
{

}


void Foam::totalenergy::write()
{

}

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