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

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

// VTK include
#include <vtkTransform.h>
#include <vtkTransformFilter.h>

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

using namespace camitk;


// --------------- Constructor -------------------
SaveDisplacementFromTransformation::SaveDisplacementFromTransformation(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Save Displacement From Transformation");
    setDescription(tr("Save the displacement from the last translation in a text file. Alternatively, load a transformation from \
                   a text file and apply it on the selected Mesh component."));
    setComponentClassName("MeshComponent");

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

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

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

// --------------- getWidget -------------------
QWidget* SaveDisplacementFromTransformation::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* loadTransformationButton = new QPushButton(tr("Load Transformation"));
        QPushButton* outputFileButton         = new QPushButton(tr("Output File"));
        outputFileLineEdit = new QLineEdit();

        actionWidget->layout()->addWidget(loadTransformationButton);
        actionWidget->layout()->addWidget(outputFileButton);
        actionWidget->layout()->addWidget(outputFileLineEdit);

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

    return actionWidget;
}


// --------------- apply -------------------
Action::ApplyStatus SaveDisplacementFromTransformation::apply() {
    for (Component* comp : getTargets()) {
        MeshComponent* input = dynamic_cast<MeshComponent*>(comp);
        process(input);
    }

    return SUCCESS;
}

// --------------- openTransformation -------------------
void SaveDisplacementFromTransformation::openTransformation() {
    // get the transformation file name
    inputFileName = QFileDialog::getOpenFileName(nullptr, "Load Transformation");
}

// --------------- outputTransformation -------------------
void SaveDisplacementFromTransformation::outputTransformation() {
    QString ofile = QFileDialog::getSaveFileName(nullptr, tr("Save As Ansys..."), QString(), "Displacement in Ansys batch format (*.txt)");

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

// --------------- outputFileChanged -------------------
void SaveDisplacementFromTransformation::outputFileChanged(const QString& oFile) {
    outputFileName = oFile;
}

// --------------- process -------------------
Action::ApplyStatus SaveDisplacementFromTransformation::process(MeshComponent* comp) {
    if (inputFileName.isEmpty() || outputFileName.isEmpty()) {
        CAMITK_ERROR(tr("Please provide a transformation file and a output file name to process \"%1\"").arg(comp->getName()))
        return ERROR;
    }
    else {
        std::ifstream in(inputFileName.toStdString().c_str());

        vtkSmartPointer<vtkTransform> transfo = vtkSmartPointer<vtkTransform>::New();
        double x, y, z, t;
        for (unsigned int i = 0; i < 4; i++) {
            in >> x >> y >> z >> t;
            transfo->GetMatrix()->SetElement(i, 0, x);
            transfo->GetMatrix()->SetElement(i, 1, y);
            transfo->GetMatrix()->SetElement(i, 2, z);
            transfo->GetMatrix()->SetElement(i, 3, t);
        }

        std::ofstream os(outputFileName.toStdString().c_str());

        // 0. compute the tranformation (=the lazy way to compute it)
        vtkSmartPointer<vtkPointSet> ps = comp->getPointSet();

        // Actually transform the points of the VTK dataset
        vtkSmartPointer<vtkTransformFilter> transformFilter = vtkSmartPointer<vtkTransformFilter>::New();
        transformFilter->SetTransform(transfo);
        transformFilter->SetInputData(ps);

        transformFilter->Update();

        vtkSmartPointer<vtkPoints> newPts = transformFilter->GetOutput()->GetPoints();
        vtkSmartPointer<vtkPoints> currentPts = ps->GetPoints();

        // 1. compute the displacement and save it
        double newPos[3];
        double currentPos[3];

        for (int i = 0; i < newPts->GetNumberOfPoints(); i++) {
            // get the current position
            currentPts->GetPoint(i, currentPos);
            // get the new position
            newPts->GetPoint(i, newPos);

            // INDEX +1 because of Ansys!!!!
            // put the displacement in the os, in Ansys displacement format
            os << "D,  " << i + 1 << ", , " << newPos[0] - currentPos[0] << " \t, , , ,UX, , , , , " << std::endl;
            os << "D,  " << i + 1 << ", , " << newPos[1] - currentPos[1] << " \t, , , ,UY, , , , , " << std::endl;
            os << "D,  " << i + 1 << ", , " << newPos[2] - currentPos[2] << " \t, , , ,UZ, , , , , " << std::endl;
        }

        return SUCCESS;
    }

}


