/*****************************************************************************
 * $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 "MshComponent.h"
#include "MshExtension.h"

//-- Qt
#include <QFileInfo>

//-- VTK
#include <vtkCellType.h>
#include <vtkCell.h>

//-- CamiTK
#include <Log.h>
using namespace camitk;

// --------------- getName -------------------
QString MshExtension::getName() const {
    return "Msh Component";
}

// --------------- getDescription -------------------
QString MshExtension::getDescription() const {
    return tr("This simple MSH Component allows you to manipulate <em>.msh</em> files (initially from gmsh software). See <a href=\"http://www.geuz.org/gmsh/doc/texinfo/gmsh.html\">http://www.geuz.org/gmsh/doc/texinfo/gmsh.html</a> for more information about this format");
}

// --------------- getFileExtensions -------------------
QStringList MshExtension::getFileExtensions() const {
    QStringList ext;
    ext << "msh";
    return ext;
}

// --------------- open -------------------
Component* MshExtension::open(const QString& fileName) {
    return new MshComponent(fileName);
}

// --------------- save --------------------
bool MshExtension::save(Component* component) const {
    MeshComponent* meshComp = dynamic_cast<MeshComponent*>(component);
    vtkSmartPointer<vtkPointSet> ps =  meshComp->getPointSet();

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

    std::ofstream mshFile(meshComp->getFileName().toStdString().c_str());
    double xyz[3];
    mshFile << "$NOD" << endl;
    mshFile << ps->GetPoints()->GetNumberOfPoints() << endl;
    for (int i = 0; i < ps->GetPoints()->GetNumberOfPoints(); i++) {
        ps->GetPoints()->GetPoint(i, xyz);
        mshFile << i + 1 << " " << xyz[0] << " " << xyz[1] << " " << xyz[2] << endl;
    }
    mshFile << "$ENDNOD" << endl;
    mshFile << "$ELM" << endl;

    // compute the number of cells, removing the unsupported types
    unsigned int numberOfExportedCells = 0;
    for (vtkIdType i = 0; i < ps->GetNumberOfCells() ; i++) {
        int cellType = ps->GetCell(i)->GetCellType();
        if (cellType == VTK_LINE || cellType == VTK_TETRA || cellType == VTK_HEXAHEDRON || cellType == VTK_WEDGE || cellType == VTK_PYRAMID || cellType == VTK_TRIANGLE || cellType == VTK_QUAD) {
            numberOfExportedCells++;
        }
    }

    mshFile << numberOfExportedCells << endl;
    for (vtkIdType i = 0; i < ps->GetNumberOfCells() ; i++) {
        bool supportedType = true;
        switch (ps->GetCell(i)->GetCellType()) {
            case VTK_LINE :
                mshFile << i + 1 << " 1 1 1 2";
                break;
            case VTK_TETRA :
                mshFile << i + 1 << " 4 1 1 4";
                break;
            case VTK_HEXAHEDRON :
                mshFile << i + 1 << " 5 1 1 8";
                break;
            case VTK_WEDGE :
                mshFile << i + 1 << " 6 1 1 6";
                break;
            case VTK_PYRAMID :
                mshFile << i + 1 << " 7 1 1 5";
                break;
            case VTK_TRIANGLE :
                mshFile << i + 1 << " 2 1 1 3";
                break;
            case VTK_QUAD :
                mshFile << i + 1 << " 3 1 1 4";
                break;
            default:
                supportedType = false;
                CAMITK_WARNING(tr("Unsupported element type for cell #%1 (type=%2): this cell was not exported to msh").arg(QString::number(i), QString::number(ps->GetCell(i)->GetCellType())))
                break;
        }
        if (supportedType) {
            for (vtkIdType j = 0; j < ps->GetCell(i)->GetNumberOfPoints(); j++) {
                mshFile << " " << ps->GetCell(i)->GetPointId(j) + 1;
            }
            mshFile << endl;
        }
    }

    mshFile << "$ENDELM" << endl;
    mshFile.close();

    return true;
}
