/*****************************************************************************
* $CAMITK_LICENCE_BEGIN$
*
* CamiTK - Computer Assisted Medical Intervention ToolKit
* (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
*
* Visit http://camitk.imag.fr for more information
*
* This file is part of CamiTK.
*
* CamiTK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* CamiTK 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 Lesser General Public License version 3 for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
*
* $CAMITK_LICENCE_END$
****************************************************************************/

#include "ObjExtension.h"
#include "ObjComponent.h"

#include <Log.h>

#include <QFileInfo>

#include <vtkGeometryFilter.h>
#include <vtkTriangleFilter.h>
#include <vtkCell.h>
#include <vtkCleanPolyData.h>

// --------------- getName -------------------
QString ObjExtension::getName() const {
    return "Alias Wavefront OBJ Component";
}

// --------------- getDescription -------------------
QString ObjExtension::getDescription() const {
    return tr("Manage Alias Wavefront OBJ <em>.obj</em> files in <b>CamiTK</b>.<br/>(very few support!)");
}

// --------------- getFileExtensions -------------------
QStringList ObjExtension::getFileExtensions() const {
    QStringList ext;
    ext << "obj";
    return ext;
}

// --------------- open -------------------
camitk::Component* ObjExtension::open(const QString& fileName) {
    return new ObjComponent(fileName);
}

// --------------- save -------------------
bool ObjExtension::save(camitk::Component* component) const {

    if (component->getPointSet() == nullptr || component->getPointSet()->GetNumberOfPoints() == 0 || component->getPointSet()->GetNumberOfCells() == 0) {
        CAMITK_WARNING(tr("Save as obj: the selected component does not have any points or cells. This is an invalid mesh."))
        return false;
    }

    QString baseFilename = QFileInfo(component->getFileName()).absolutePath() + "/" + QFileInfo(component->getFileName()).completeBaseName();
    QString fileName = baseFilename + ".obj";

    vtkSmartPointer< vtkGeometryFilter > geoFilter = vtkSmartPointer< vtkGeometryFilter >::New();
    vtkSmartPointer< vtkTriangleFilter > triangleFilter = vtkSmartPointer< vtkTriangleFilter >::New();

    // first we apply a geometry filter to keep only polygonal cells
    geoFilter->SetInputData(component->getPointSet());
    // then a triangle filter to transform the polygones in triangles
    triangleFilter->SetInputConnection(geoFilter->GetOutputPort());
    triangleFilter->PassLinesOff();
    triangleFilter->PassVertsOff();
    triangleFilter->Update();
    bool saveOk = true;

    vtkSmartPointer<vtkPolyData> poly = triangleFilter->GetOutput();
    vtkSmartPointer<vtkCleanPolyData> cleanFilter = vtkSmartPointer<vtkCleanPolyData>::New();

    // Apply a vtkCleanPolyData to merge duplicate points created by the triangleFilter operation
    // This may also replace triangles by lines if they are flat
    cleanFilter->SetInputData(poly);
    cleanFilter->Update();

    std::ofstream objFile(fileName.toUtf8());
    double xyz[3];
    objFile << "# Object 3D file generated by CamiTK" << endl;
    objFile << "# number of vertices : " << cleanFilter->GetOutput()->GetPoints()->GetNumberOfPoints() << endl;
    objFile << "# number of faces : " << cleanFilter->GetOutput()->GetNumberOfCells() << endl;

    // write vertices
    for (int i = 0; i < cleanFilter->GetOutput()->GetPoints()->GetNumberOfPoints(); i++) {
        cleanFilter->GetOutput()->GetPoints()->GetPoint(i, xyz);
        objFile << "v " << xyz[0] << " " << xyz[1] << " " << xyz[2] << endl;
    }
    objFile << endl;

    for (vtkIdType i = 0; i < cleanFilter->GetOutput()->GetNumberOfCells(); i++) {
        switch (cleanFilter->GetOutput()->GetCell(i)->GetCellType()) {
            case VTK_TRIANGLE:
                objFile << "f";
                for (vtkIdType j = 0; j < cleanFilter->GetOutput()->GetCell(i)->GetNumberOfPoints(); j++) {
                    objFile << " " << cleanFilter->GetOutput()->GetCell(i)->GetPointId(j) + 1;    // << "//" << cleanFilter->GetOutput()->GetCell(i)->GetPointId(j) + 1;
                }
                objFile << endl;
                break;
            default:
                // Some cells are not triangles: probably due to vtkCleanPolyData replacing empty triangles by lines
                saveOk = false;
                break;
        }
    }

    objFile.close();
    if (!saveOk) {
        CAMITK_WARNING(tr("The OBJ file format only support triangles cells, empty triangles were not saved.\nTopology may have been altered."))
    }

    return saveOk;
}
