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

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

// VTK includes
#include <vtkTransform.h>
#include <vtkPolyData.h>
#include <vtkTransformFilter.h>
#include <vtkDataSet.h>
#include <vtkUnstructuredGrid.h>

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

using namespace camitk;

// --------------- Constructor -------------------
LoadTransformation::LoadTransformation(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Load Transformation");
    setDescription(tr("Load a transformation from a file. The file should contains the 4x4 matrix values (4 lines of 4 values). See also the \"Save Displacement From Transformation\" action."));
    setComponentClassName("MeshComponent");

    // Setting classification family and tags
    setFamily("Mesh Processing");
    addTag("translation");
    addTag("rotation");
    addTag("load from file");

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

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

// --------------- openTransformation -------------------
void LoadTransformation::openTransformation() {

    // get the transformation file name
    transformationFile = QFileDialog::getOpenFileName(nullptr, "Load Transformation");
}

// --------------- apply -------------------
Action::ApplyStatus LoadTransformation::apply() {

    if (!transformationFile.isEmpty()) {
        //-- load the transformation
        std::ifstream in(transformationFile.toStdString().c_str());

        vtkSmartPointer<vtkTransform> transformation = vtkSmartPointer<vtkTransform>::New();
        double x, y, z, t;

        for (unsigned int i = 0; i < 4; i++) {
            in >> x >> y >> z >> t;
            transformation->GetMatrix()->SetElement(i, 0, x);
            transformation->GetMatrix()->SetElement(i, 1, y);
            transformation->GetMatrix()->SetElement(i, 2, z);
            transformation->GetMatrix()->SetElement(i, 3, t);
        }

        //-- apply the transformation to all targets
        for (Component* comp : getTargets()) {
            MeshComponent* targetMesh = dynamic_cast<MeshComponent*>(comp);

            if (targetMesh) {

                // apply a vtk transform filter and get the result
                vtkSmartPointer<vtkTransformFilter> vtkFilter = vtkSmartPointer<vtkTransformFilter>::New();
                vtkFilter->SetTransform(transformation);
                vtkFilter->SetInputConnection(targetMesh->getDataPort());
                targetMesh->setDataConnection(vtkFilter->GetOutputPort());

                vtkSmartPointer<vtkPointSet> result = vtkPointSet::SafeDownCast(vtkFilter->GetOutputDataObject(0));

                if (result) {
                    targetMesh->setPointSet(result);
                }

                targetMesh->setModified();
            }
        }
    }
    else {
        CAMITK_WARNING(tr("Transformation file is missing, please provide one."))
        return ABORTED;
    }

    return SUCCESS;
}

// --------------- getWidget -------------------
QWidget* LoadTransformation::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* loadtransformation = new QPushButton("Load Transformation");

        actionWidget->layout()->addWidget(loadtransformation);
        QObject::connect(loadtransformation, SIGNAL(released()), SLOT(openTransformation()));
    }
    else {
        // make sure the widget has updated targets
        dynamic_cast<ActionWidget*>(actionWidget)->update();
    }

    return actionWidget;
}

