/*****************************************************************************
 * $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$
 ****************************************************************************/

#ifndef IMAGE_COMPONENT_H
#define IMAGE_COMPONENT_H

// -- Core image component stuff
#include "CamiTKAPI.h"
#include "Component.h"
#include "ImageOrientationHelper.h"

// -- vtk stuff
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkImageData.h>
#include <vtkTransform.h>
#include <vtkImageFlip.h>
#include <vtkWindowLevelLookupTable.h>
#include <vtkMatrix4x4.h>
#include <vtkUnstructuredGrid.h>
#include <vtkActor.h>

// -- QT stuff classes
class QMenu;
class QTableView;
class QVector3D;
class QVariant;
class QTableView;
class QStandardItemModel;

namespace camitk {

class MeshComponent;
class SingleImageComponent;
class ArbitrarySingleImageComponent;

/**
 * @ingroup group_sdk_libraries_core_component_image
 *
 * @brief
 * The manager of the Image Volume data.
 * An image volume data has no concrete 3D representation, as its representation 
 * is provided by its sub-components (axial, sagittal, coronal and arbitrary slices as well as volume rendering).
 *
 * It builds a complete/ready-to-use VTK pipeline: @see Slice
 *
 * @note
 * You can use the following properties to change the visualization of an ImageComponent and children components:
 * - "Display Image in 3D Viewer" type boolean, controls what is displayed in the default 3D viewer
 *
 * Every time a property is changed using setProperty(QString propertyName, QVariant value), the ImageComponent
 * will automatically update, thanks to the propertyValueChanged(..) method.
 */
class CAMITK_API ImageComponent : public camitk::Component {
    Q_OBJECT

public:

    /** Creates an ImageComponent from a file.
     *  This method is called from a ComponentExtension derived class that support the
     *  given file format.
     *
     *  This method may throw an AbortException if a problem occurs.
     *
     * @param file the complete path to the image file
     * @param name name to be given to the Component (this name will appear in the explorer)
     */
    ImageComponent(const QString& file, const QString& name);

    /** Creates an ImageComponent from a vtkImageData.
     *     
     * By default, does not copy the original image, but references the corresponding
     * smart pointer (for memory reasons, but if copy is set to true,
     * performs a deep copy).
     *
     * This method may throw an AbortException if a problem occurs.
     *
     * @param anImageData volume image of the new ImageComponent
     * @param name name to be given to the Component (this name will appear in the explorer)
     * @param copy perform or not a deep copy of the image given in parameters.
     * @param initialOrientation the initial orientation of the image. This information may be stored in the file header or in some time (DICOM). If no orientation information is provided, assume the image orientation is RAI.
     */
    ImageComponent(vtkSmartPointer<vtkImageData> anImageData, const QString& name, bool copy = false, ImageOrientationHelper::PossibleImageOrientations initialOrientation = ImageOrientationHelper::RAI);

    /// Destructor
    ~ImageComponent() override;

    /// set selected will select all the Image components (axial, sagittal and coronal).
    void setSelected(const bool b, const bool recursive = false) override;

    /// set the visibility inside the viewer of the given name  (override required to manage the specific case of the 3D viewer)
    virtual void setVisibility(QString, bool) override;

    /// get the image volume managed by this Component
    vtkSmartPointer<vtkImageData> getImageData() const override {
        return originalImageData;
    }

    /**
     * Compute a copy of the original image data on which the frame transform has been applied.
     * This allows one to keep all the frame transform information on the file when saving it.
     * @return a vtkImageData deep copied from the original image data on which the frame transform has been applied.
     */
    vtkSmartPointer<vtkImageData> getImageDataWithFrameTransform();

    /// Get the initial image orientation
    ImageOrientationHelper::PossibleImageOrientations getInitialOrientation() const {
        return initialOrientation;
    }

    /** Method called when a pixel has been picked in the 3D view.
     * This method tells all the scene3D to display the slice containing the picked pixel.
     * The arguments are the coordinates of the 3D point.
     */
    void pixelPicked(double x, double y, double z) override;

    /** Get a vtkActor to display a 3D cursor at the last picked position
     * If the last picked pixel is invalid, this returns a nullptr
     */
    virtual vtkSmartPointer<vtkActor> get3DCursor() override;

    /// Get the last pixel picked using CTRL + LEFT/RIGHT CLICK in voxel index
    /// (i, j, k) indicates the voxel index (no notion of voxel size)
    void getLastPixelPicked(int* x, int* y, int* z);

    /// Get the last point picked using CTRL + LEFT/RIGHT CLICK in the data frame coordinates
    /// (this takes into account voxel size)
    void getLastPointPickedDataFrame(double* x, double* y, double* z);

    /// Get Get the last point picked using CTRL + LEFT/RIGHT CLICK in the world coordinates
    /// This takes into account voxel size and image origin (and possible image rigid transforms).
    void getLastPointPickedWorldFrame(double* x, double* y, double* z);

    /// Set the last point picked coordinates to the center of the x,y,z voxel
    void setLastPointPickedFromPixel(int x, int y, int z);

    /** Number of colors: number of possible gray levels in the image
     *  computed from the min and the max of the data type ;
     *  e.g. for a volume coded on unsigned char, returns 256.
     */
    int getNumberOfColors() const override;

    /** Min possible gray level of the image given its data type */
    double getMinColor() const;

    /** Max possible gray level of the image given its data type */
    double getMaxColor() const;

    /** Actual Number of colors: difference betweent the maximun and
     * the minimum gray levels found in the image.
     */
    int getActualNumberOfColors() const;

    /** Min gray level found in the image given its data type */
    double getActualMinColor() const;

    /** Max gray level found in the image given its data type */
    double getActualMaxColor() const;

    /** Number of axial slices (i.e. dim[2]) */
    int getNumberOfSlices() const override;

    /// Update the lookup table of the image viewer (see InterfaceBitMap).
    virtual void setLut(vtkSmartPointer<vtkWindowLevelLookupTable> lookupTable);

    /// get the current lookup table
    virtual vtkSmartPointer<vtkWindowLevelLookupTable>  getLut();

    /// get the current lookup table (const version)
    virtual const vtkSmartPointer<vtkWindowLevelLookupTable>  getLut() const;

    /// force refresh of all interactive viewers that are displaying sub-components
    /// as ImageComponent is not itself displayed by any viewer
    void refresh() override;

    /** Returns the axial slice */
    SingleImageComponent* getAxialSlices();
    /** Returns the coronal slice */
    SingleImageComponent* getCoronalSlices();
    /** Returns the sagittal slice */
    SingleImageComponent* getSagittalSlices();
    /** Returns the arbitrary slice */
    ArbitrarySingleImageComponent* getArbitrarySlices();
    /** Returns the MeshComponent which will contain the volume rendering actor */
    MeshComponent* getVolumeRenderingChild();

    /** Replaces the current image volume by the one given in parameters
     *  @param anImageData the replacement image data
     *  @param copy if it is set to true, performs a deep copy before replacing the image. If copy is set to false, only takes the smart pointer as input.
     *  @param initialOrientation the initial orientation of the replacement image. If no orientation information is provided, assume the image orientation is RAI.
     */
    virtual void replaceImageData(vtkSmartPointer<vtkImageData> anImageData, bool copy = false, ImageOrientationHelper::PossibleImageOrientations initialOrientation = ImageOrientationHelper::RAI);

    /**
      * @name InterfaceProperty
      * InterfaceProperty implemented methods
      */
    ///@{
    /// manages dynamic property viewIn3D
    void propertyValueChanged(QString) override;

    /// return number of tabs in property explorer: there is more than one widget
    unsigned int getNumberOfPropertyWidget() override;

    /// get the property widget (to view as tabs in the property explorer): the default property widget and the selection view
    QWidget* getPropertyWidgetAt(unsigned int i) override;
    ///@}

    const vtkSmartPointer<vtkMatrix4x4> getRotationMatrix() {
        return rotationMatrix;
    }

    /**
     * * @name Frame management
     * Override to force subComponents to have the same data and main frame than this Component
     */
    ///@{
    /// set the main and data FrameOfReference as well as the transformation between them
    virtual void setFramesAndTransformation(const std::shared_ptr<FrameOfReference>& mainFrame, const std::shared_ptr<FrameOfReference>& dataFrame,  const std::shared_ptr<Transformation>& mainTransformation);

    /// get the data FrameOfReference (i.e., the vtkImageData frame)
    const FrameOfReference* getDataFrame() const {
        return dataFrame.get();
    };

    /// set the main FrameOfReference overriden to manage subcomponents
    /// @warning if the transformation from the data frame to the new main frame already exists, it
    /// will be used as the new main transformation, removing the previous main transformation
    /// If there is currently no transformation from the data frame to the new main frame,
    /// it will try to create a new main transformation using the same matrix.
    /// If this cannot be done, this generates a CamiTK error
    virtual void setFrame(const std::shared_ptr<FrameOfReference>& frame) override;

    // Modify this object's frame using the given object's frame.
    /// \note if the given object is an ImageComponent, this will call setFramesAndTransformation
    /// using the object main and data frame and its main transformation
    virtual void setFrameFrom(const InterfaceFrame*) override;

    /// Reset this object's FrameOfReference, that is call setFrame with a newly created frame of reference.
    /// \note if the given object is an ImageComponent, this will call setFramesAndTransformation
    /// using newly created main and data frames, and a new transformation (preserving the current main transformation matrix)
    virtual void resetFrame() override;

    /// get the other frames (neither data nor main)
    virtual const std::vector<std::shared_ptr<FrameOfReference>>& getAdditionalFrames() const {
        return additionalFrames;
    };

    /// add an additional frame (neither data nor main)
    virtual void addAdditionalFrame(const std::shared_ptr<FrameOfReference>& fr) {
        additionalFrames.push_back(fr);
    }

    /// remove an additional frame
    virtual void removeAdditionalFrame(const FrameOfReference* fr) {
        std::erase_if(additionalFrames, [fr](auto & f) {
            return f.get() == fr;
        });
    }

    /// get the additional Transformations
    virtual const std::vector<std::shared_ptr<Transformation>>& getAdditionalTransformations() const {
        return additionalTransformations;
    }

    /// add an additional Transformation
    virtual void addAdditionalTransformation(const std::shared_ptr<Transformation> tr) {
        additionalTransformations.push_back(tr);
    }

    /// Remove an additional Transformation from the Component
    virtual void removeAdditionalTransformation(const Transformation* tr) {
        std::erase_if(additionalTransformations, [tr](auto t) {
            return t.get() == tr;
        });
    }

    /// Get all FrameOfReference owned by this image
    /// @arg includeChildrenFrames Include the frames of this image's children along with its own
    ////@return A multimap that associates each FrameOfReference to the Components that own it
    virtual QMultiMap<const FrameOfReference*, Component*> getAllFrames(bool includeChildrenFrames = true) override;

    /// Get all Transformation owned by this image
    /// @arg includeChildrenTransformations Include the Transformation of this image's children along with its own
    ////@return A multimap that associates each Transformation to the Components that own it
    virtual QMultiMap<const Transformation*, Component*> getAllTransformations(bool includeChildrenTransformations = true) override;

    /// Get main Transformation (data -> main)
    virtual Transformation* getMainTransformation() const {
        return mainTransformation.get();
    }

    /// update the main transformation using the given 4x4 matrix
    virtual void updateMainTransformation(vtkSmartPointer<vtkMatrix4x4>);
    ///@}

    /**
     * * @name InterfacePersistence
     * Customized InterfacePersistence methods to support LUT
     */
    ///@{
    /// Convert all data from the object to a QVariant (usually a QVariantMap)
    virtual QVariant toVariant() const override;

    /// Load data from a QVariant to initialize the current object
    virtual void fromVariant(const QVariant&) override;
    ///@}

protected:

    /**
     * Set the image data of the volumic images with the given orientation options.
     * @param anImageData The main vtkImageData of the volumic image.
     * @param copy Indicate if we do a vtk deep copy of these data or directly work on the one provided.
     * @param initialOrientation Initial image orientation
     * @param initialTransformMatrix Initial image rotation (provided as a 4x4 matrix)
     */
    void setImageData(vtkSmartPointer<vtkImageData> anImageData,
                      bool copy,
                      ImageOrientationHelper::PossibleImageOrientations initialOrientation = ImageOrientationHelper::RAI,
                      vtkSmartPointer<vtkMatrix4x4> initialTransformMatrix = nullptr);

    /** Set all single images.
     *  The only time this method should be used is when you redefined the SingleImageComponent class.
     *  <b>Warning:</b> this overwrite the original single image components.
     *  <b>Note:</b> if you need to change only one of these SingleImageComponent instances, you'd better use the getter methods on the remaining instances.
     *  @param axialSlices the axial slices representation (use getAxialSlices() if you don't need to modify this particular orientation)
     *  @param sagittalSlices the sagittal slices representation (use getSagittalSlices() if you don't need to modify this particular orientation)
     *  @param coronalSlices the coronal slices representation (use getCoronalSlices() if you don't need to modify this particular orientation)
     *  @param arbitrarySlices the arbitrary slices representation (use getArbitrarySlices() if you don't need to modify this particular orientation)
     */
    void setSingleImageComponents(SingleImageComponent* axialSlices, SingleImageComponent* sagittalSlices, SingleImageComponent* coronalSlices, ArbitrarySingleImageComponent* arbitrarySlices);

    /// Set main Transformation (dataFrame -> mainFrame)
    /// return false if the main transformation was not modified (that is tr was nullptr)
    bool setMainTransformation(const std::shared_ptr<Transformation>& tr);

private:
    /** Update the Properties displayed in the PropertyExplorer
     *   It should be called by setImageData to update the properties with respect to the new image data
     *   The properties updated are:
     *  - Image Name
     *  - Image Dimensions
     *  - Image Size
     *  - Voxel Size
     *  - Voxel Data Type
     *  - Display Image in 3D Viewer
     */
    void initImageProperties();

    /// the concrete building of the 3D objects (Slice/Geometry): none in this case!
    void initRepresentation() override {}

    // builds default lookup table
    void initLookupTable();

    /// Create the 3D cursor
    void initCursor();

    /// Update the cursor, to be called when the picked point changed or the voxel size changed
    void updateCursor();

    /// build the SingleImageComponent (one for each image plane);
    void buildImageComponents();

    /// update the image components vtkImageData of all the available SingleImageComponent
    void updateImageComponents();

    /** Update visibility in the 3D viewer.
     *  Depending on the value of the "Display Image in 3D Viewer" property
     *  and the available SingleImageComponent actually instantiated, this method
     *  will update the visibility of the SingleImageComponent in the default 3D viewer.
     */
    void update3DViewer();

    /// internal method used to put a mesh in volumeRenderingChild
    /// and accessoiry display the bounding box
    vtkSmartPointer<vtkPolyData> getBoundingBox();

    /// the core Image Volume that is managed here
    vtkSmartPointer<vtkImageData> originalImageData;

    /// the axial slices representation (all intelligence is delegated to a Slice class instance)
    SingleImageComponent* axialSlices;

    /// the sagittal slices representation (all intelligence is delegated to a Slice class instance)
    SingleImageComponent* sagittalSlices;

    /// the coronal slices representation (all intelligence is delegated to a Slice class instance)
    SingleImageComponent* coronalSlices;

    /// the arbitrary slices representation (all intelligence is delegated to a Slice class instance)
    ArbitrarySingleImageComponent* arbitrarySlices;

    /// When an action computes volume rendering for an image,
    ///     it stores the corresponding actor as a prop of this Component.
    MeshComponent* volumeRenderingChild;

    /// the current lookup table
    vtkSmartPointer<vtkWindowLevelLookupTable> lut;

    /// Store the coordinates of the center of the last selected pixel in the data FrameOfReference
    double currentPixelPicked[3];

    /// 3D cursor actor
    vtkSmartPointer<vtkActor> cursorActor;

    /// 3D cursor actor unstructured grid
    vtkSmartPointer<vtkUnstructuredGrid> cursorActorPointSet;

    /// initialize pointers to nullptr and other attributes
    void init();

    /// Tab displaying data selected point in the property explorer
    QTableView* selectionView;

    /// Model to display data
    QStandardItemModel* model;

    /// Initial image orientation
    ImageOrientationHelper::PossibleImageOrientations initialOrientation;

    /// The initial transform to the vtkImageData
    /// @note This transform is equal to the initial image translation (Offset)
    /// multiplies by the reorientation transform (transform -> RAI)
    vtkSmartPointer<vtkTransform> initialImageDataTransform;

    /// The initial frame of the image at opening
    /// @note This transform is equal to the initial image translation (Offset)
    /// multiplies by its rotation (TransformMatrix)
    /// multiplies by the reorientation transform (transform -> RAI)
    vtkSmartPointer<vtkTransform> initialFrameTransform;

    /// The rotation matrix, that might have been altered by the user
    /// Will be saved in header file information as TransformMatrix tag.
    vtkSmartPointer<vtkMatrix4x4> rotationMatrix;

    // InterfaceFrame extension for Images
    std::shared_ptr<FrameOfReference> dataFrame = nullptr;
    std::shared_ptr<Transformation> mainTransformation = nullptr;
    std::vector<std::shared_ptr<FrameOfReference>> additionalFrames;
    std::vector<std::shared_ptr<Transformation>> additionalTransformations;
};

}

#endif //IMAGE_COMPONENT_H
