/*****************************************************************************
 * $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 "component_bindings.h"
#include "core_utils.h"
#include "qt_bindings.h"
#include "numpy_utils.h"
#include "docstrings.h"

#include <Application.h>
#include <Component.h>
#include <TransformationManager.h>
#include <ImageComponent.h>
#include <ArbitrarySingleImageComponent.h>
#include <SingleImageComponent.h>
#include <MeshComponent.h>

namespace camitk {

/// This trampoline class is required for having python Component derived class as
/// Component has a pure virtual method
class PyComponent : public camitk::Component {
    using camitk::Component::Component;  // inherit constructors

private:
    virtual void initRepresentation() override {
        // as initRepresentation is private it cannot be export to python, just do nothing.
    }
};

} // namespace camitk

void add_component_bindings(py::module_& m) {

    // --------------- Component ---------------

    // need all hierarchy so that pybind11 can ensure polymorphism
    py::class_<camitk::InterfaceProperty /* also inherits from QObject, but silenced here as not needed in python and probably extremely difficult to do! */ >(m, "InterfaceProperty", DOC(camitk_InterfaceProperty));

    py::class_<camitk::InterfaceNode>(m, "InterfaceNode", DOC(camitk_InterfaceNode));

    py::class_<camitk::InterfaceGeometry> interfaceGeometry(m, "InterfaceGeometry", DOC(camitk_InterfaceGeometry));

    py::enum_<camitk::InterfaceGeometry::RenderingMode> renderingMode(interfaceGeometry, "RenderingMode", py::arithmetic(), DOC(camitk_InterfaceGeometry_RenderingMode));
    renderingMode.value("NoRenderingMode", camitk::InterfaceGeometry::RenderingMode::None);
    renderingMode.value("Surface", camitk::InterfaceGeometry::RenderingMode::Surface);
    renderingMode.value("Wireframe", camitk::InterfaceGeometry::RenderingMode::Wireframe);
    renderingMode.value("Points", camitk::InterfaceGeometry::RenderingMode::Points);
    renderingMode.export_values();

    py::class_<camitk::InterfaceBitMap>(m, "InterfaceBitMap", DOC(camitk_InterfaceBitMap));

    py::class_<camitk::InterfaceFrame>(m, "InterfaceFrame", DOC(camitk_InterfaceFrame));

    py::class_<camitk::InterfacePersistence>(m, "InterfacePersistence", DOC(camitk_InterfacePersistence));

    py::class_<camitk::Component, camitk::PyComponent,
    camitk::InterfaceProperty, camitk::InterfaceNode, camitk::InterfaceGeometry, camitk::InterfaceBitMap, camitk::InterfaceFrame, camitk::InterfacePersistence> component(m, "Component", DOC(camitk_Component));

    component.def(py::init<const QString, const QString>(), DOC(camitk_Component_Component_1));

    // Note: use the InterfaceClass docstrings for inherited methods
    // as the doxygen parser cannot always associate the docstring
    // to the corresponding inherited method
    component.def("getName", &camitk::Component::getName,
                  DOC(camitk_InterfaceNode_getName));

    component.def("setName", [](camitk::Component & self, QString newName) {
        QString uniqueName = camitk::Application::getUniqueComponentName(newName);
        self.setName(uniqueName);
    },
    DOC(camitk_InterfaceNode_setName));

    component.def("getFileName", &camitk::Component::getFileName,
                  DOC(camitk_Component_getFileName));

    component.def("setFrameFrom", &camitk::Component::setFrameFrom,
                  DOC(camitk_InterfaceFrame_setFrameFrom));

    component.def("getFrame", &camitk::Component::getFrame,
                  py::return_value_policy::reference,
                  DOC(camitk_InterfaceFrame_getFrame));

    component.def("setFrame", [](camitk::Component & self, camitk::FrameOfReference * framePtr) {
        std::shared_ptr<camitk::FrameOfReference> frameSharedPtr = camitk::TransformationManager::getFrameOfReferenceOwnership(framePtr);
        self.setFrame(frameSharedPtr);
        // Note: the application should be refreshed to see the effect in the viewers
    },
    DOC(camitk_InterfaceFrame_setFrame));

    component.def("getPropertyValue", &camitk::Component::getPropertyValue,
                  DOC(camitk_InterfaceProperty_getPropertyValue));

    component.def("setPropertyValue", &camitk::Component::setPropertyValue,
                  DOC(camitk_InterfaceProperty_setPropertyValue));

    component.def("setModified", &camitk::Component::setModified
                  , DOC(camitk_Component_setModified));

    component.def("refresh", &camitk::Component::refresh,
                  DOC(camitk_Component_refresh));

    component.def("addChild", &camitk::Component::addChild,
                  DOC(camitk_InterfaceNode_addChild));

    component.def("getChildren", &camitk::Component::getChildren,
                    py::return_value_policy::reference,
                    DOC(camitk_InterfaceNode_getChildren));

    component.def("getParent", &camitk::Component::getParent,
                    py::return_value_policy::reference,
                    DOC(camitk_InterfaceNode_getParent));

    component.def("isTopLevel", &camitk::Component::isTopLevel,
                    DOC(camitk_Component_isTopLevel));

    component.def("isSelected", &camitk::Component::isSelected,
                    DOC(camitk_Component_isSelected));

    component.def("setSelected", &camitk::Component::setSelected,
                    py::arg("b"), 
                    py::arg("recursive") = true,
                    DOC(camitk_Component_setSelected));

    // --------------- ImageComponent ---------------

    py::class_<camitk::ImageComponent, camitk::Component> imageComponent(m, "ImageComponent", DOC(camitk_ImageComponent));

    // Note : the docstrings of this constructor was not retrieved properly
    // by the docstring generator -> it needs to be added manually here.
    imageComponent.def(py::init<const QString&, const QString&>(),
                       DOC(camitk_ImageComponent_ImageComponent_1));

    imageComponent.def("clone", [](camitk::ImageComponent & self) {
        QString cloneName = camitk::Application::getUniqueComponentName(self.getName());
        camitk::ImageComponent* clone = new camitk::ImageComponent(self.getImageData(), cloneName);
        clone->setFrameFrom(&self);
        return clone;
    },
    py::return_value_policy::reference,
    R"doc(Clone this original image. Note that the image data is not copied, only referenced from the clone, and that the frame of the clone is set to the original image component's frame.)doc");

    imageComponent.def("getImageDataAsNumpy",
    [](camitk::ImageComponent & self) {
        return camitk::vtkImageDataToNumpy(self.getImageData());
    },
    R"doc(Returns the image data as a numpy ndarray.)doc");

    imageComponent.def("getSpacing",
    [](camitk::ImageComponent & self) {
        return camitk::getVtkImageDataSpacing(self.getImageData());
    },
    R"doc(Returns the image spacing as a tuple of 3 floats (spacingX, spacingY, spacingZ).)doc");

    imageComponent.def("getDimensions",
    [](camitk::ImageComponent & self) {
        int dim[3];
        self.getImageData()->GetDimensions(dim);
        return py::make_tuple(dim[0], dim[1], dim[2]);
    },
    R"doc(Returns the image dimensions as a tuple of 3 integers (dimX, dimY, dimZ).)doc");

    imageComponent.def("replaceImageData",
    [](camitk::ImageComponent * self, const py::array & numpyArray) {
        vtkSmartPointer<vtkImageData> imgData = camitk::numpyToVTKImageData(numpyArray);
        self->replaceImageData(imgData, true);
        // FIXME CamiTK Core: 3D viewer actor is not updated properly, copy is always required
        self->refresh();
    },
    R"doc(Replaces the image data with the given numpy ndarray.)doc");

    imageComponent.def("getDataFrame", &camitk::ImageComponent::getDataFrame,
                       py::return_value_policy::reference,
                       DOC(camitk_ImageComponent_getDataFrame));

    // TODO should this helper method be added in ImageComponent as well?
    imageComponent.def("getArbitrarySliceFrame", [](camitk::ImageComponent & self) {
        return self.getArbitrarySlices()->getArbitraryFrame();
    },
    py::return_value_policy::reference,
    R"doc(Returns the FrameOfReference used for the arbitrary slice.)doc");

    imageComponent.def("getLastPixelPicked", [](camitk::ImageComponent & self) {
        int i, j, k;
        self.getLastPixelPicked(&i, &j, &k);
        return py::make_tuple(i, j, k);
    },
    DOC(camitk_ImageComponent_getLastPixelPicked));

    imageComponent.def("getLastPointPickedDataFrame", [](camitk::ImageComponent & self) {
        double x, y, z;
        self.getLastPointPickedDataFrame(&x, &y, &z);
        return py::make_tuple(x, y, z);
    },
    DOC(camitk_ImageComponent_getLastPointPickedDataFrame));

    imageComponent.def("getLastPointPickedWorldFrame", [](camitk::ImageComponent & self) {
        double x, y, z;
        self.getLastPointPickedWorldFrame(&x, &y, &z);
        return py::make_tuple(x, y, z);
    },
    DOC(camitk_ImageComponent_getLastPointPickedWorldFrame));

    // --------------- MeshComponent ---------------

    py::class_<camitk::MeshComponent, camitk::Component> meshComponent(m, "MeshComponent", DOC(camitk_MeshComponent));

    meshComponent.def("setRenderingModes", [](camitk::MeshComponent & self, int modes) {
        self.setRenderingModes(camitk::InterfaceGeometry::RenderingModes(modes));
    },
    DOC(camitk_InterfaceGeometry_setRenderingModes));

    meshComponent.def("clone", [](camitk::MeshComponent & self) {
        QString cloneName = camitk::Application::getUniqueComponentName(self.getName());
        camitk::MeshComponent* clone = new camitk::MeshComponent(self.getPointSet(), cloneName);
        clone->setFrameFrom(&self);
        return clone;
    },
    py::return_value_policy::reference,
    R"doc(Clone this original mesh. Note that the point set is not copied, only referenced from the clone, and that the frame of the clone is set to the original mesh component's frame.)doc");

    meshComponent.def("getPointSetAsNumpy",
    [](camitk::MeshComponent & self) {
        return camitk::vtkPointSetToNumpy(self.getPointSet());
    },
    R"doc(Returns the point set as a numpy ndarray of shape (N, 3) where N is the number of points.)doc");

    meshComponent.def("replacePointSet",
    [](camitk::MeshComponent & self, const py::array & numpyArray) {
        vtkSmartPointer<vtkPoints> points = camitk::numpyToVtkPoints(numpyArray);
        self.getPointSet()->SetPoints(points);

        // check if this is a point cloud
        vtkSmartPointer<vtkPolyData> polyData = vtkPolyData::SafeDownCast(self.getPointSet());
        if (polyData != nullptr && self.getPointSet()->GetNumberOfCells() == 1) {
            // this is a point cloud, update the verts
            vtkNew<vtkCellArray> verts;
            verts->InsertNextCell(points->GetNumberOfPoints());
            for (vtkIdType i = 0; i < points->GetNumberOfPoints(); ++i) {
                verts->InsertCellPoint(i);
            }
            polyData->SetVerts(verts);
        }

        self.getPointSet()->Modified();
        self.refresh();
    },
    R"doc(Replaces the point set with the given numpy ndarray of shape (N, 3) where N is the number of points. If there is no Cell/polygons, this will be interpreted as a point cloud (it will create one cell containing all the points).)doc");

    meshComponent.def("setColor", [](camitk::MeshComponent & self, const QColor & newColor) {
        double actorColor[4];
        actorColor[0] = newColor.redF();
        actorColor[1] = newColor.greenF();
        actorColor[2] = newColor.blueF();
        actorColor[3] = newColor.alphaF();
        self.setActorColor(self.getRenderingModes(), actorColor);
    },
    DOC(camitk_InterfaceGeometry_setActorColor_1));

    meshComponent.def("getColor", [](camitk::MeshComponent & self) {
        double actorColor[4];
        self.getActorColor(self.getRenderingModes(), actorColor);
        QColor currentColor;
        currentColor.setRgbF(actorColor[0], actorColor[1], actorColor[2], actorColor[3]);
        return currentColor;
    },
    DOC(camitk_InterfaceGeometry_getActorColor));

    meshComponent.def("setLinesAsTubes", &camitk::MeshComponent::setLinesAsTubes,
                      py::arg("isTubes") = true,
                      py::arg("radiusFromLength") = true,
                      py::arg("radiusFactor") = 1.0 / 40.0,
                      py::arg("numberOfSides") = 5,
                      DOC(camitk_InterfaceGeometry_setLinesAsTubes));

    // enum
    // TODO change to enum_native when updating binding to pybind3
    // see https://pybind11.readthedocs.io/en/stable/classes.html#enumerations-and-internal-types
    py::enum_<camitk::MeshComponent::FieldType> fieldType(meshComponent, "FieldType",
            DOC(camitk_MeshComponent_FieldType));
    fieldType.value("POINTS", camitk::MeshComponent::POINTS);
    fieldType.value("CELLS", camitk::MeshComponent::CELLS);
    fieldType.value("MESH", camitk::MeshComponent::MESH);
    fieldType.export_values();

    meshComponent.def("getNumberOfDataArray", &camitk::MeshComponent::getNumberOfDataArray,
                      DOC(camitk_MeshComponent_getNumberOfDataArray));

    meshComponent.def("getDataArray", [](camitk::MeshComponent & self, camitk::MeshComponent::FieldType field, int index) {
        vtkSmartPointer<vtkDataArray> dataArray = self.getDataArray(field, index);
        return camitk::vtkDataArrayToNumpy(dataArray);
    },
    R"doc(Get the data array of specified field type and index as a numpy ndarray.)doc");

    meshComponent.def("addDataArray", [](camitk::MeshComponent & self, camitk::MeshComponent::FieldType field, const QString & name, const py::array & numpyArray) {
        self.addDataArray(field, name, camitk::numpyToVtkDataArray(numpyArray));
    },
    R"doc(Add a data array using the given a numpy ndarray.)doc");

    meshComponent.def("removeDataArray", &camitk::MeshComponent::removeDataArray,
                      DOC(camitk_MeshComponent_removeDataArray));

    meshComponent.def("addPointData", [](camitk::MeshComponent & self, const QString & name, const py::array & numpyArray) {
        self.addPointData(name, camitk::numpyToVtkDataArray(numpyArray));
    },
    R"doc(Adds a point data array using the given numpy ndarray.)doc");

    meshComponent.def("addCellData", [](camitk::MeshComponent & self, const QString & name, const py::array & numpyArray) {
        self.addCellData(name, camitk::numpyToVtkDataArray(numpyArray));
    },
    R"doc(Adds a cell data array using the given numpy ndarray.)doc");

    meshComponent.def("setDataRepresentationOff", &camitk::MeshComponent::setDataRepresentationOff,
                      py::arg("dataType") = camitk::MeshComponent::SCALARS | camitk::MeshComponent::VECTORS | camitk::MeshComponent::TENSORS,
                      py::arg("blockRefresh") = false,
                      DOC(camitk_MeshComponent_setDataRepresentationOff));

    meshComponent.def("getPickedPointId", &camitk::MeshComponent::getPickedPointId,
                      DOC(camitk_MeshComponent_getPickedPointId));

    meshComponent.def("getPickedPointPosition", [](camitk::MeshComponent & self) {
        double position[3] { 0.0, 0.0, 0.0 };
        if (self.getPickedPointId() >= 0 && self.getPickedPointId() < self.getPointSet()->GetNumberOfPoints()) {
            self.getPointSet()->GetPoint(self.getPickedPointId(), position);
        }
        return py::make_tuple(position[0], position[1], position[2]);
    },
    R"doc(Returns the position of the picked point as a tuple of 3 floats (x, y, z) in this mesh component frame. If no point is picked, returns (0.0, 0.0, 0.0).)doc");

    meshComponent.def("getPickedCellId", &camitk::MeshComponent::getPickedCellId,
                      DOC(camitk_MeshComponent_getPickedCellId));

    // --------------- Utils ---------------

    m.def("newImageComponentFromNumpy",
          &camitk::newImageComponentFromNumpy,
          py::arg("array"),  // extract the array part of the dict
          py::arg("name") = "image",
          py::arg("spacing") = py::none(), // by default no spacing have to be given
          py::return_value_policy::reference,
          R"doc(Create an Image Component by creating a new vtkImageData from the given array of voxel and spacing, if provided))doc");

    m.def("newMeshComponentFromNumpy",
          &camitk::newMeshComponentFromNumpy,
          py::arg("name") = "mesh",
          py::arg("points_array"),
          py::arg("polys_array") = py::array(),
          py::return_value_policy::reference,
          R"doc(Creates a Mesh Component by creating a new vtkPointSet made of the given point array and poly array(only vtkPolyData and point clouds are supported for now))doc");

}

