/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | www.openfoam.com
     \\/     M anipulation  |
-------------------------------------------------------------------------------
    Copyright (C) 2011-2016 OpenFOAM Foundation
    Copyright (C) 2020 OpenCFD Ltd.
-------------------------------------------------------------------------------
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/>.

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

#include "gpuskewCorrectionVectors.H"
#include "volgpuFields.H"

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

namespace Foam
{
    defineTypeNameAndDebug(gpuskewCorrectionVectors, 0);
}


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

Foam::gpuskewCorrectionVectors::gpuskewCorrectionVectors(const gpufvMesh& mesh)
:
    MeshObject<gpufvMesh, Foam::MoveableMeshObject, gpuskewCorrectionVectors>(mesh),
    skew_(false),
    skewCorrectionVectors_
    (
        IOobject
        (
            "skewCorrectionVectors",
            mesh_.hostmesh().pointsInstance(),
            mesh_.hostmesh(),
            IOobject::NO_READ,
            IOobject::NO_WRITE,
            false
        ),
        mesh_,
        dimless
    )
{
    calcSkewCorrectionVectors();
}


Foam::gpuskewCorrectionVectors::~gpuskewCorrectionVectors()
{}


namespace Foam
{
struct skewCorrectionVectorsFunctor{
    __host__ __device__
    vector operator()(const thrust::tuple<vector,vector,vector,vector>& t){
        vector d = thrust::get<0>(t) - thrust::get<1>(t);
        vector Cpf = thrust::get<2>(t) - thrust::get<1>(t);

        return Cpf - ((thrust::get<3>(t) & Cpf)/(thrust::get<3>(t) & d))*d;
    }
};

struct skewCorrectionVectorsPatchFunctor{
    __host__ __device__
    vector operator()(const thrust::tuple<vector,vector,vector,vector>& t){
        vector Cpf = thrust::get<0>(t) - thrust::get<1>(t);

        return Cpf
                  - (
                        (thrust::get<2>(t) & Cpf)/
                        (thrust::get<2>(t) & thrust::get<3>(t))
                    )*thrust::get<3>(t);
    }
};
}

void Foam::gpuskewCorrectionVectors::calcSkewCorrectionVectors()
{
    DebugInFunction << "Calculating skew correction vectors" << nl;

    // Set local references to mesh data
    const volVectorgpuField& C = mesh_.C();
    const surfaceVectorgpuField& Cf = mesh_.Cf();
    const surfaceVectorgpuField& Sf = mesh_.Sf();

    const labelgpuList& owner = mesh_.owner();
    const labelgpuList& neighbour = mesh_.neighbour();

    thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(thrust::make_permutation_iterator(C.field().begin(),neighbour.begin()),
                                                                   thrust::make_permutation_iterator(C.field().begin(),owner.begin()),
                                                                   Cf.field().begin(),
                                                                   Sf.field().begin()
                                                                  )
                                                ),
                      thrust::make_zip_iterator(thrust::make_tuple(thrust::make_permutation_iterator(C.field().begin(),neighbour.begin()+owner.size()),
                                                                   thrust::make_permutation_iterator(C.field().begin(),owner.end()),
                                                                   Cf.field().end(),
                                                                   Sf.field().end()
                                                                   )
                                                ),
                      skewCorrectionVectors_.field().begin(),
                      skewCorrectionVectorsFunctor());


    surfaceVectorgpuField::Boundary& skewCorrVecsBf =
        skewCorrectionVectors_.boundaryFieldRef();

    forAll(skewCorrVecsBf, patchi)
    {
        fvsPatchVectorgpuField& patchSkewCorrVecs = skewCorrVecsBf[patchi];

        if (!patchSkewCorrVecs.coupled())
        {
            patchSkewCorrVecs = Zero;
        }
        else
        {
            const gpufvPatch& p = patchSkewCorrVecs.patch();
            const labelgpuList& faceCells = p.gpuFaceCells();
            const vectorgpuField& patchFaceCentres = Cf.boundaryField()[patchi];
            const vectorgpuField& patchSf = Sf.boundaryField()[patchi];
            const vectorgpuField patchD(p.delta());
             
            thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(patchFaceCentres.begin(),
                                                                   thrust::make_permutation_iterator(C.field().begin(),faceCells.begin()),
                                                                   patchSf.begin(),
                                                                   patchD.begin()
                                                                  )
                                                ),
                      thrust::make_zip_iterator(thrust::make_tuple(patchFaceCentres.end(),
                                                                   thrust::make_permutation_iterator(C.field().begin(),faceCells.end()),
                                                                   patchSf.end(),
                                                                   patchD.end()
                                                                   )
                                                ),
                      patchSkewCorrVecs.begin(),
                      skewCorrectionVectorsPatchFunctor());
        }
    }

    scalar skewCoeff = 0.0;

    if (Sf.primitiveField().size())
    {
        skewCoeff =
            max(mag(skewCorrectionVectors_)*mesh_.deltaCoeffs()).value();
    }

    DebugInFunction << "skew coefficient = " << skewCoeff << nl;

    if (skewCoeff < 1e-5)
    {
        skew_ = false;
    }
    else
    {
        skew_ = true;
    }

    if (debug)
    {
        Info<< "    Finished constructing skew correction vectors" << endl;
    }
}


bool Foam::gpuskewCorrectionVectors::movePoints()
{
    calcSkewCorrectionVectors();
    return true;
}


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