/*****************************************************************************
 * $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 "ExportAsMDL.h"

// Qt includes
#include <QFileDialog>
#include <QPushButton>
#include <QLayout>

// CamiTK includes
#include <ActionWidget.h>
#include <MeshComponent.h>
#include <Log.h>

// Vtk includes
#include <vtkGeometryFilter.h>
#include <vtkTriangleFilter.h>
#include <vtkCleanPolyData.h>
#include <vtkPointData.h>
#include <vtkPolyDataNormals.h>
#include <vtkCell.h>

using namespace camitk;


// --------------- Constructor -------------------
ExportAsMDL::ExportAsMDL(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Export As MDL");
    setDescription(tr("Export As MDL (an old legacy file format from early CAMI devices). This is kept for historical reason only."));
    setComponentClassName("MeshComponent");

    // Setting classification family and tags
    setFamily("Mesh Processing");

    // DO NOT Put any GUI instantiation here,
    // If you need, do it in getWidget() method, using lazy instantiation
}

// --------------- destructor -------------------
ExportAsMDL::~ExportAsMDL() {
    // Do not do anything yet.
    // Delete stuff if you create stuff
    // (except if you use smart pointers of course !!)
}

// --------------- getWidget -------------------
QWidget* ExportAsMDL::getWidget() {
    // Use lazy instantiation (instantiate only once and when needed)
    // We will return the default action widget with an additionnal button

    // build or update the widget
    if (actionWidget == nullptr) {
        // Setting the widget containing the parameters, using the default widget
        actionWidget = new ActionWidget(this);

        QPushButton* outputbutton = new QPushButton("Output file");
        outputfile = new QLineEdit();

        actionWidget->layout()->addWidget(outputbutton);
        actionWidget->layout()->addWidget(outputfile);

        QObject::connect(outputbutton, SIGNAL(released()), SLOT(outputMDL()));
        QObject::connect(outputfile, SIGNAL(textChanged(QString)), this, SLOT(outputFileChanged(QString)));
    }
    else {
        // make sure the widget has updated targets
        dynamic_cast<ActionWidget*>(actionWidget)->update();
    }

    return actionWidget;
}

// --------------- outputMDL -------------------
void ExportAsMDL::outputMDL() {

    QString ofile = QFileDialog::getSaveFileName(nullptr, tr("Save As MDL..."), QString(), tr("MDL format(*.mdl)"));

    if (!ofile.isEmpty()) {
        outputfile->setText(ofile);
    }
}

// --------------- outputFileChanged -------------------
void ExportAsMDL::outputFileChanged(const QString& ofile) {
    filename = ofile;
}

// --------------- apply -------------------
Action::ApplyStatus ExportAsMDL::apply() {
    Action::ApplyStatus returnStatus = SUCCESS;

    for (Component* comp : getTargets()) {
        MeshComponent* input = dynamic_cast<MeshComponent*>(comp);
        if (input != nullptr) {
            returnStatus = process(input);
        }
        else {
            CAMITK_WARNING(tr("Target component \"%1\" is of type \"%2\": \"MeshComponent\" expected. Action aborted.").arg(comp->getName(), comp->getHierarchy().value(0)))
            returnStatus = ABORTED;    // Bad input (should not be possible)
        }
    }

    return returnStatus;
}

// --------------- process -------------------
Action::ApplyStatus ExportAsMDL::process(MeshComponent* comp) {

    if (!filename.isEmpty()) {
        // if the filename does not have the ".mdl" extension, add it
        QFileInfo fileinfo(filename);
        if (fileinfo.suffix() != ".mdl") {
            filename += ".mdl";
        }
        saveMeshComponentToMDL(comp);
        return SUCCESS;
    }
    else {
        CAMITK_WARNING("Output file is missing, please provide one. Action aborted.");
        return ABORTED;
    }
}

// --------------- saveMeshComponentToMDL -------------------
void ExportAsMDL::saveMeshComponentToMDL(MeshComponent* comp) {

    int i;
    // MDL format supports only triangles. Hence, this dataset triangularized before
    // being exported (this operation is then NOT reversible).
    // if the dataset is a volumetric mesh (e.g. hexahedrons), only the external surface is exported.

    //extract external surface
    vtkSmartPointer<vtkGeometryFilter> geomF = vtkSmartPointer<vtkGeometryFilter>::New();
    geomF->SetInputData(comp->getPointSet());

    // triangles
    vtkSmartPointer<vtkTriangleFilter> triangleF = vtkSmartPointer<vtkTriangleFilter>::New();
    triangleF->SetInputData(geomF->GetOutput());

    // clean unused
    vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New();
    cleaner->SetInputData(triangleF->GetOutput());
    cleaner->Update();

    vtkSmartPointer<vtkPolyData> ds = cleaner->GetOutput();

    //--- write as .mdl file (Registration format)
    std::ofstream o(filename.toUtf8().constData());

    //--- name
    o << "[Name, STRING]" << std::endl;
    o << comp->getName().toStdString() << std::endl;
    o << std::endl;

    double pt[3];

    //--- vertices
    o << "[Vertices, ARRAY1<POINT3D>]" << std::endl;
    if (ds->GetPoints() != nullptr) {
        o << ds->GetPoints()->GetNumberOfPoints() << std::endl;


        for (i = 0; i < ds->GetPoints()->GetNumberOfPoints(); i++) {
            ds->GetPoints()->GetPoint(i, pt);
            o << pt[0] << " " << pt[1] << " " << pt[2] << std::endl;
        }
    }
    o << std::endl;

    //--- normals
    o << "[Normals, ARRAY1<VECTOR3D>]" << std::endl;

    if (ds->GetPointData() && ds->GetPointData()->GetNormals()) {
        // save existing normals
        o << ds->GetPointData()->GetNormals()->GetNumberOfTuples() << std::endl;

        for (i = 0; i < ds->GetPointData()->GetNormals()->GetNumberOfTuples(); i++) {
            ds->GetPointData()->GetNormals()->GetTuple(i, pt);
            o << pt[0] << " " << pt[1] << " " << pt[2] << std::endl;
        }
    }
    else {
        // compute the normals
        vtkSmartPointer<vtkPolyDataNormals> pNormals = vtkSmartPointer<vtkPolyDataNormals>::New();
        pNormals->SetInputData(ds);
        pNormals->Update();

        if (pNormals->GetOutput()->GetPointData() != nullptr && pNormals->GetOutput()->GetPointData()->GetNormals() != nullptr) {
            o << pNormals->GetOutput()->GetPointData()->GetNormals()->GetNumberOfTuples() << std::endl;

            for (i = 0; i < pNormals->GetOutput()->GetPointData()->GetNormals()->GetNumberOfTuples(); i++) {
                pNormals->GetOutput()->GetPointData()->GetNormals()->GetTuple(i, pt);
                o << pt[0] << " " << pt[1] << " " << pt[2] << std::endl;
            }
        }

    }

    o << std::endl;


    //--- triangles
    int j;
    o << "[Triangles, ARRAY1<STRING>]" << std::endl;
    o << ds->GetNumberOfCells() << std::endl;

    for (i = 0; i < ds->GetNumberOfCells(); i++) {
        // write it twice
        for (j = 0; j < ds->GetCell(i)->GetNumberOfPoints(); j++) {
            o << ds->GetCell(i)->GetPointId(j) << " ";
        }

        for (j = 0; j < ds->GetCell(i)->GetNumberOfPoints(); j++) {
            o << ds->GetCell(i)->GetPointId(j) << " ";
        }

        o << std::endl;
    }

}

