/*****************************************************************************
 * $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 <MeshComponent.h>
#include <Log.h>
#include <Application.h>

// disable warning generated by clang about the surrounded headers
#include <CamiTKDisableWarnings>
#include <vtkExtractEdges.h>
#include <CamiTKReEnableWarnings>

#include <vtkUnstructuredGrid.h>
#include <vtkGeometryFilter.h>
#include <vtkCleanPolyData.h>
#include <vtkCallbackCommand.h>

using namespace camitk;

#include "ExtractEdges.h"

ExtractEdges::ExtractEdges(ActionExtension* extension) : Action(extension) {
    this->setName("Extract Edges");
    this->setDescription(tr("Extract edges from a mesh"));
    this->setComponentClassName("MeshComponent");
    this->setFamily("Mesh Processing");
    this->addTag(tr("ExtractEdges"));
}


Action::ApplyStatus ExtractEdges::apply() {
    // set waiting cursor and status bar
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    Application::showStatusBarMessage(tr("Extracting edges..."));
    Application::resetProgressBar();
    vtkSmartPointer<vtkCallbackCommand> progressCallback = vtkSmartPointer<vtkCallbackCommand>::New();
    progressCallback->SetCallback(&Application::vtkProgressFunction);

    // use the last target
    MeshComponent* targetMesh = dynamic_cast<MeshComponent*>(getTargets().last());

    vtkSmartPointer<vtkExtractEdges> extractEdgesFilter = vtkSmartPointer<vtkExtractEdges>::New();
    extractEdgesFilter->SetInputData(targetMesh->getPointSet());
    extractEdgesFilter->AddObserver(vtkCommand::ProgressEvent, progressCallback);
    extractEdgesFilter->Update();

    // create a new mesh Component
    new MeshComponent(extractEdgesFilter->GetOutput(), targetMesh->getName() + " edges");
    refreshApplication();

    // restore the normal cursor and progress bar
    Application::resetProgressBar();
    Application::showStatusBarMessage("");
    QApplication::restoreOverrideCursor();
    return SUCCESS;
}
