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

// -- Application --
#include <Application.h>
#include <InteractiveSliceViewer.h>
#include <Component.h>
#include <MeshComponent.h>
#include <ImageComponent.h>
#include <SingleImageComponent.h>
#include <Transformation.h>
#include <TransformationManager.h>
#include <Log.h>
#include <Property.h>
#include <RendererWidget.h>
#include <ActionWidget.h>

// -- vtk stuff --
// disable warning generated by clang about the surrounded headers
#include <CamiTKDisableWarnings>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderWindow.h>
#include <vtkOrientedGlyphContourRepresentation.h>
#include <vtkWidgetEventTranslator.h>
#include <vtkEvent.h>
#include <vtkProperty.h>
#include <CamiTKReEnableWarnings>

#include <vtkContourWidget.h>
#include <vtkPolyData.h>

//-- Qt
#include <QBoxLayout>
#include <QFrame>
#include <QVector3D>

#include <iostream>

using namespace camitk;

// --------------- constructor ---------------
ContourWidget::ContourWidget(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Contour Widget");
    setDescription(R"(<p>Add a VTK Contour widget in a 2D viewer to interactively define a region contour. The contour follows the selected slice.</p>
    <p>First select the 2D viewer and then click <tt>Apply</tt> to start the contour creation:</p>
    <ul>
        <li>Click Apply and then left click in the chosen viewer to add the first contour node</li>
        <li>Left Click: Add/select a point</li>
        <li>Right Click: Add final point</li>
        <li>Middle Click: Translate the contour</li>
        <li>Close Contour Widget: Join the start and end handles interactively</li>
        <li><tt>Delete Contour Widget</tt> button: Delete the current contour widget. This will allow you to start again from scratch in any viewer you like. It will detach the generated mesh component and leave it in its current state without deleting it. <b>Note:</b> it is not possible to re-attach it later.</li>
        <li><tt>Duplicate Contour Widget</tt>Same as <tt>Delete Contour Widget</tt> but will create a new contour and mesh component from the current contour widget shape. This can be useful to use the current contour as the initialization for the next slice. Once the contour is duplicate, change the slice to move it to the next image slice</li>
    </ul>
    <p>You may change the color and size an any time, click <tt>Apply</tt> to update the contour. You cannot change the viewer until you click on <tt>Delete Contour Widget</tt> (or close the generated Mesh Component).</p>)");
    setComponentClassName("ImageComponent");

    // Setting classification family and tags
    setFamily("Tutorial");
    addTag("Demo");
    addTag("Segmentation");
    addTag("2D Interaction");
    addTag("VTK Widget");

    Property* viewerProperty = new Property("Viewer", 0, "The viewer in which the contour is going to be created", "");
    viewerProperty->setEnumTypeName("ViewerList");
    // add strings to populate the GUI
    // axial = 0, coronal = 1, sagittal = 2
    viewerProperty->setAttribute("enumNames", getViewerNameList());
    addParameter(viewerProperty);

    addParameter(new Property("Contour Color", QColor(250.0, 150.0, 50.0), tr("Color of the contour (default is orange)"), ""));
    addParameter(new Property("Line Width", 2.0, tr("Contour line width"), ""));

    Property* nbOfPointsProperty = new Property("Number Of Points", 0, "Number of points in the current contour (updated automatically when the contour is interactively modified).", "");
    nbOfPointsProperty->setReadOnly(true);
    addParameter(nbOfPointsProperty);

    contourWidget = nullptr;
    contourWidgetCommand = nullptr;
    frontPlanePlacer = nullptr;
    selectedViewer = -1;

    //-- widget lazy instantiation
    myWidget = nullptr;

    //-- currently selected image
    currentImage = nullptr;
    currentMesh = nullptr;
}

// --------------- getWidget ---------------
QWidget* ContourWidget::getWidget() {
    // update image
    ImageComponent* selectedImage = dynamic_cast<ImageComponent*>(getTargets().last());

    // check if the current image is still the same
    if (selectedImage != currentImage) {
        // change contour
        deleteContour();
        // update image
        currentImage = selectedImage;
    }

    // create widget
    if (myWidget == nullptr) {
        //-- the frame
        myWidget = new QFrame();
        myWidget->setFrameShape(QFrame::StyledPanel);
        myWidget->setFrameShadow(QFrame::Sunken);
        myWidget->setLineWidth(3);

        //-- the vertical layout, put every GUI elements in it
        auto* informationFrameLayout = new QVBoxLayout();

        // add the default action widget
        informationFrameLayout->addWidget(Action::getWidget());

        // add two other specific actions
        QPushButton* closeContour = new QPushButton("Close Contour Widget");
        informationFrameLayout->addWidget(closeContour);
        QObject::connect(closeContour, SIGNAL(released()), this, SLOT(closeContour()));

        QPushButton* deleteContour = new QPushButton("Delete Contour Widget");
        deleteContour->setWhatsThis("Delete the current contour widget.<br/>This will allow you to start again from scratch in the viewer you like.<br/>It will detach the generated mesh component and leave it in its current state.<br/><b>Note:</b> it is not possible to re-attach it later.");
        deleteContour->setToolTip("Delete the current contour widget.<br/>This will allow you to start again from scratch in the viewer you like.<br/>It will detach the generated mesh component and leave it in its current state.<br/><b>Note:</b> it is not possible to re-attach it later.");
        informationFrameLayout->addWidget(deleteContour);
        QObject::connect(deleteContour, SIGNAL(released()), this, SLOT(deleteContour()));

        QPushButton* duplicateContour = new QPushButton("Duplicate Contour Widget");
        duplicateContour->setWhatsThis("Same as \"Delete Contour Widget\" but will create a new contour and mesh component from the current contour widget shape.<br/>This can be useful to use the current contour as the initialization for the next slice.");
        duplicateContour->setToolTip("Same as \"Delete Contour Widget\" but will create a new contour and mesh component from the current contour widget shape.<br/>This can be useful to use the current contour as the initialization for the next slice.");
        informationFrameLayout->addWidget(duplicateContour);
        QObject::connect(duplicateContour, SIGNAL(released()), this, SLOT(duplicateContour()));

        //-- set the layout for the action widget
        myWidget->setLayout(informationFrameLayout);
    }

    return myWidget;
}

// --------------- apply ---------------
Action::ApplyStatus ContourWidget::apply() {
    //-- update the contour
    if (contourWidget == nullptr) {
        if (!initContour()) {
            return ABORTED;
        }
    }

    //-- create/update the transformed mesh
    if (currentMesh == nullptr) {
        // create mesh for the first time
        initMesh();
    }

    update();

    return SUCCESS;
}

// --------------- initContour ---------------
bool ContourWidget::initContour() {
    // start from scratch
    deleteContour();

    //-- set the viewer and interactor depending on the viewer chosen by the user
    selectedViewer = getParameterValue("Viewer").toInt();
    QString selectedViewerName = getViewerName();
    InteractiveSliceViewer* selectedInteractiveViewer = dynamic_cast<InteractiveSliceViewer*>(Application::getViewer(selectedViewerName));
    if (selectedInteractiveViewer == nullptr) {
        CAMITK_ERROR(tr("Cannot find \"%1\". This viewer is mandatory for creating a 2D contour.").arg(selectedViewerName))
        selectedViewer = -1;
        return false;
    }
    vtkRenderWindowInteractor* interactor = selectedInteractiveViewer->getRendererWidget()->getInteractor();

    //-- create contour
    contourWidget = vtkSmartPointer<vtkContourWidget>::New();
    contourWidget->SetInteractor(interactor);

    //-- create 3D representation either from scratch or from the given polydata
    contourWidget->EnabledOn();
    contourWidget->CreateDefaultRepresentation();
    contourWidget->FollowCursorOn();

    //-- add the callback
    contourWidgetCommand = new ContourWidgetVtkCommand(this);
    contourWidget->AddObserver(vtkCommand::EndInteractionEvent, contourWidgetCommand);

    vtkSmartPointer<vtkOrientedGlyphContourRepresentation> contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());
    frontPlanePlacer = vtkSmartPointer<vtkBoundedPlanePointPlacer>::New();
    contourRep->SetPointPlacer(frontPlanePlacer);

    // set the displacement plane
    switch (selectedViewer) {
        case 1:
            // Coronal is y plane
            frontPlanePlacer->SetProjectionNormalToYAxis();
            break;
        case 2:
            // Sagittal is x plane
            frontPlanePlacer->SetProjectionNormalToXAxis();
            break;
        case 0:
        default:
            // Axial and default is z
            frontPlanePlacer->SetProjectionNormalToZAxis();
            break;
    }

    // connect the viewer selection changed
    connect(selectedInteractiveViewer, SIGNAL(selectionChanged()), this, SLOT(update()));

    // once the contour is set, the property should be read only until the contour is deleted
    // although this has no effect as the ObjectController cannot produce read only enum GUI
    getProperty("Viewer")->setReadOnly(true);
    getProperty("Viewer")->setAttribute("enumNames", { selectedInteractiveViewer->getName() });
    getProperty("Viewer")->setDescription(QString("%1 was selected to create the current contour. Please click on Restart to create a new contour in another viewer.").arg(selectedInteractiveViewer->getName()));

    // refresh all viewers
    refreshApplication();

    return true;
}

// --------------- updateContourAndMesh ---------------
void ContourWidget::updateContourAndMesh() {
    // the contour is defined in the image data frame and is positioned in 3D
    // by a translation that depends on the viewer and selected slice
    updateTransformation();

    // change color of the VTK widget representation and current mesh using the current user choice
    QColor contourColor = property("Contour Color").value<QColor>();
    auto contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());

    contourRep->GetLinesProperty()->SetColor(contourColor.redF(), contourColor.greenF(), contourColor.blueF());
    // Use white vertex which is more visible
    contourRep->GetActiveProperty()->SetColor(1.0, 1.0, 1.0); // active handle
    contourRep->GetProperty()->SetColor(1.0, 1.0, 1.0);       // passive handle

    // change line width of the contour widget
    float lineWidth = property("Line Width").toFloat();
    contourRep->GetLinesProperty()->SetLineWidth(lineWidth);
    contourRep->GetProperty()->SetPointSize(lineWidth * 2); // force point size to double line size to make them more visible even when contour is greenish

    // update contour after forcing the computation of the new mesh
    contourRep->BuildRepresentation(); // same effect as: contourWidget->Render();
    currentMesh->setPointSet(contourRep->GetContourRepresentationAsPolyData());

    // update mesh color 3D actor color
    currentMesh->setColor(contourColor.redF(), contourColor.greenF(), contourColor.blueF());

    // update mesh 3D actor line width
    if (currentMesh->getActor(InterfaceGeometry::Surface) != nullptr) {
        currentMesh->getActor(InterfaceGeometry::Surface)->GetProperty()->SetLineWidth(lineWidth);
    }
}

// --------------- deleteContour ---------------
void ContourWidget::deleteContour() {
    // if already present reset observers and start from scratch
    if (contourWidget != nullptr) {
        contourWidget->RemoveObserver(contourWidgetCommand);
        contourWidget->Off();
        contourWidget = nullptr;
        contourWidgetCommand = nullptr;
        frontPlanePlacer = nullptr;
        currentMesh = nullptr;
        // disconnect
        disconnect(Application::getViewer(getViewerName()), SIGNAL(selectionChanged()), this, SLOT(update()));
        selectedViewer = -1;

        // release viewer property
        getProperty("Viewer")->setReadOnly(false);
        getProperty("Viewer")->setAttribute("enumNames", getViewerNameList());
        getProperty("Viewer")->setDescription("The viewer in which the contour is going to be created");
        dynamic_cast<camitk::ActionWidget*>(Action::getWidget())->update();

        // refresh all viewers
        refreshApplication();
    }
}

// --------------- initMesh ---------------
void ContourWidget::initMesh() {

    QString meshName = currentImage->getName();
    switch (selectedViewer) {
        case 1:
            meshName += " Coronal " + QString::number(currentImage->getCoronalSlices()->getSlice());
            break;
        case 2:
            meshName += " Sagittal " + QString::number(currentImage->getSagittalSlices()->getSlice());
            break;
        case 0:
        default:
            meshName += " Axial " + QString::number(currentImage->getAxialSlices()->getSlice());
            break;
    }

    // get vtkPointSet from the contour output to crate the new mesh component
    vtkSmartPointer<vtkOrientedGlyphContourRepresentation> contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());
    currentMesh = new MeshComponent(contourRep->GetContourRepresentationAsPolyData(), meshName);

    // the mesh is defined directly to the data image frame as the contour widget is drawn in
    // the 2D viewer, i.e. the data image data
    currentMesh->setFrame(TransformationManager::getFrameOfReferenceOwnership(currentImage->getDataFrame()));
    // Note : this can also be accomplished by creating an identity transformation in the
    // transformation information system that goes from data image frame to mesh frame:
    // TransformationManager::addTransformation(currentImage->getDataFrame(), currentMesh->getFrame());
    // This identity transform will place the mesh at the same place as the data image frame
    // and therefore placing it as if it was defined directly in the data image frame.

    // TODO When saving a mesh on its own (not in a camitk workspace), should they be saved
    // directly in the world frame (as no mesh file format have any concept of transformation)?

    // make sure the contour will be deleted if the mesh component or image component are closed by the user
    connect(currentMesh, SIGNAL(destroyed()), this, SLOT(deleteContour()));
    connect(currentImage, SIGNAL(destroyed()), this, SLOT(deleteContour()));
}

// --------------- updateTransformation ---------------
void ContourWidget::updateTransformation() {
    // The transformation depends on
    // - the slice plane
    // - the slice id
    // The transformation is required as the contour is a widget drawn in the normal plane
    // of the current 2D viewer plane (z=0 for axial, y=0 of the coronal, x=0 of the sagittal).
    SingleImageComponent* sliceComponent = nullptr;

    // offset factor to set the translation in the middle of the current slice
    // As camera is facing +z in axial, +y in coronal but -x in sagittal it can be either +0.5 or -0.5
    double offsetFactor;

    // index of the dimension of the translation
    // 0 = sagittal (x is the normal), 1 = coronal (y is the normal) and 2 = axial (z is the normal)
    int orientationIndex = 0;
    switch (selectedViewer) {
        case 2:
            orientationIndex = 0;
            sliceComponent = currentImage->getSagittalSlices();
            // for sagittal move toward z
            offsetFactor = 1.0;
            break;
        case 1:
            // for coronal and axial move backward z
            offsetFactor = -1.0;
            sliceComponent = currentImage->getCoronalSlices();
            orientationIndex = 1;
            break;
        case 0:
        default:
            orientationIndex = 2;
            // for coronal and axial move backward z
            offsetFactor = -1.0;
            sliceComponent = currentImage->getAxialSlices();
    }

    // image dimension
    double voxelSize[3];
    currentImage->getImageData()->GetSpacing(voxelSize);

    /// slice index + 1/2 slice offset
    double sliceId = sliceComponent->getSlice() + offsetFactor * 0.5;

    double translation = sliceId * voxelSize[orientationIndex];

    // if needed ad a tenth voxelsize offset (slightly out of plane shift for proper visualization)
    // translation += offsetFactor * voxelSize[orientationIndex] / 10.0;

    // finally set the translation in the placer and force an update
    frontPlanePlacer->SetProjectionPosition(translation);
    frontPlanePlacer->UpdateInternalState();
}

// --------------- getViewerName ---------------
QString ContourWidget::getViewerName() {
    switch (selectedViewer) {
        case 1:
            return "Coronal Viewer";
            break;
        case 2:
            return "Sagittal Viewer";
            break;
        case 0:
        default:
            return "Axial Viewer";
            break;
    }
}

// --------------- getViewerNameList ---------------
QStringList ContourWidget::getViewerNameList() {
    return QStringList({ "Axial Viewer", "Coronal Viewer", "Sagittal Viewer" });
}

// --------------- closeContour ---------------
void ContourWidget::closeContour() {
    contourWidget->CloseLoop();
    update();
}

// --------------- update ---------------
void ContourWidget::update() {
    // update contour widget and mesh
    if (contourWidget != nullptr && currentMesh != nullptr) {
        updateContourAndMesh();
    }

    // update action's widget from modified property (this is not the "usual" way, normally
    // the user modify some property in the widget and the action gets the value to do
    // something. In this case, the action's property is modified by some external
    // mechanism (not the user), e.g. here the vtContourWidget, therefore the action's widget has
    // to be updated
    dynamic_cast<camitk::ActionWidget*>(Action::getWidget())->update();

    // refresh all viewers
    refreshApplication();
}

// --------------- duplicateContour ---------------
void ContourWidget::duplicateContour() {
    if (contourWidget != nullptr) {
        // backup the poly data without the (sp)line interpolation
        auto contourRep = vtkOrientedGlyphContourRepresentation::SafeDownCast(contourWidget->GetRepresentation());
        vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
        contourRep->GetNodePolyData(polyData);

        deleteContour();

        // change current color
        QColor contourColor = property("Contour Color").value<QColor>();
        setParameterValue("Contour Color", QColor::fromHsv((contourColor.hue() + 45) % 360, contourColor.saturation(), contourColor.value()));

        initContour();

        // initialize the contour with the previous one
        contourWidget->Initialize(polyData);

        initMesh();
        update();
        refreshApplication();
    }
}
