/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2024 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>

// -- 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,
 *  but handles several sub-components for axial, sagittal and coronal slices.
 *
 * Vtk Pipeline: @see Slice
 *
 * @note
 * You can use the following properties to change the visualization of an ImageComponent and children components:
 * - "Image Name" type QString
 * - "Display Image in 3D Viewer" type boolean, controls what is displayed in the default 3D viewer
 *
 * Everytime a property is changed using setProperty(QString propertyName, QVariant value), the ImageComponent
 * will automatically update, thanks to the updateProperty(..) method.
 */
class CAMITK_API ImageComponent : public camitk::Component {
    Q_OBJECT

public:
    /// constructor
    /// This method may throw an AbortException if a problem occurs.
    ImageComponent(const QString& file);

    /** Creates an ImageComponent from a vtkImageData
     *  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 apear 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.
     *      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).
     */
    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;

    ///@cond
    /**
     * TODO CAMITK_DEPRECATED. This section list all the methods marked as deprecated. They are to be removed in CamiTK 6.0
     * @deprecated
     *
     * DEPRECATED (CamiTK 6.0) -> to be removed
     * Use the setVisibility(QString, bool) method
     */
    /// set the visibility for a viewer (override required to manage the specific case of the 3D viewer)
    CAMITK_API_DEPRECATED("Please use setVisibility(QString viewerName, bool) instead")  virtual void setVisibility(Viewer*, bool) override;
    ///@endcond

    /// 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;

    /// getter/setter for the property
    QString getImageName() const;
    void setImageName(const QString&);

    /// 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 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 ccordinates of the 3D point.
     */
    void pixelPicked(double x, double y, double z) 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 image real coordinates
    /// (this takes into account voxel size)
    void getLastPointPickedImageCoords(double* x, double* y, double* z);

    /// Get Get the last point picked using CTRL + LEFT/RIGHT CLICK in world coordinates
    /// This takes into account voxel size and image origin (and possible image rigid transforms).
    void getLastPointPickedWorldCoords(double* x, double* y, double* 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 updateProperty(QString, QVariant) 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 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);

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();

    /// 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 last pixel selected, in original slices ref
    double currentPixelPicked[3];

    /// initialize pointers to NULL 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;
};

}

#endif //IMAGE_COMPONENT_H
