/*****************************************************************************
 * $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$
 ****************************************************************************/
// CamiTK includes
#include "SobelEdgeDetection.h"

#include <ItkProgressObserver.h>
#include <Property.h>

// Itk includes
#include <itkImageToVTKImageFilter.h>
#include <itkVTKImageToImageFilter.h>
#include <itkCastImageFilter.h>
#include <itkRescaleIntensityImageFilter.h>
#include <itkSobelEdgeDetectionImageFilter.h>


using namespace camitk;


// --------------- constructor -------------------
SobelEdgeDetection::SobelEdgeDetection(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Sobel Edge Detection");
    setDescription("<br>A 2D or 3D <b>edge detection using the Sobel operator</b>.<br> \
                   This filter uses the Sobel operator to calculate the image gradient and then finds the magnitude of this gradient vector. The Sobel gradient magnitude (square-root sum of squares) is an indication of edge strength..<br>");
    setComponentClassName("ImageComponent");

    // Setting classification family and tags
    this->setFamily("ITK Filter");
    this->addTag("Sobel");
    this->addTag("Edge Detection");
    this->addTag("Contours");

    Property* keepOrgVoxelTypeProperty = new Property(tr("Keep original voxel type?"), true, tr("Does the output image have the same voxel type as the input one?"), "");
    addParameter(keepOrgVoxelTypeProperty);
}

// --------------- apply -------------------
Action::ApplyStatus SobelEdgeDetection::apply() {
    for (Component* comp : getTargets()) {
        ImageComponent* input = dynamic_cast<ImageComponent*>(comp);
        process(input);
    }
    return SUCCESS;
}

void SobelEdgeDetection::process(ImageComponent* comp) {
    this->keepOrgVoxelType = getParameterValue("Keep original voxel type?").toBool();
    // ITK filter implementation using templates
    vtkSmartPointer<vtkImageData> inputImage = comp->getImageData();
    vtkSmartPointer<vtkImageData> outputImage = implementProcess(inputImage);
    ImageComponent* outputComp = new ImageComponent(outputImage, comp->getName() + "_edges");

    // same frame as input
    outputComp->setFrameFrom(comp);

    refreshApplication();

}

#include "SobelEdgeDetection.impl"

// ITK filter implementation
template <class InputPixelType, class OutputPixelType, const int dim>
vtkSmartPointer<vtkImageData> SobelEdgeDetection::itkProcess(vtkSmartPointer<vtkImageData> img) {
    vtkSmartPointer<vtkImageData> result = vtkSmartPointer<vtkImageData>::New();
    vtkSmartPointer<vtkImageData> resultImage;

    // --------------------- Filters declaration and creation ----------------------
    // Define ITK input and output image types with respect to the instantiation
    //    types of the tamplate.
    typedef itk::Image< InputPixelType,  dim > InputImageType;
    typedef itk::Image< OutputPixelType, dim > OutputImageType;

    // Convert the image from CamiTK in VTK format to ITK format to use ITK filters.
    typedef itk::VTKImageToImageFilter<InputImageType> vtkToItkFilterType;
    typename vtkToItkFilterType::Pointer vtkToItkFilter = vtkToItkFilterType::New();

    // Declare and create your own private ITK filter here...
    typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterInType;
    typename CastFilterInType::Pointer castFilterIn = CastFilterInType::New();

    typedef itk::SobelEdgeDetectionImageFilter <OutputImageType, OutputImageType> SobelEdgeDetectionImageFilterType;
    typename SobelEdgeDetectionImageFilterType::Pointer sobelFilter = SobelEdgeDetectionImageFilterType::New();

    typedef itk::RescaleIntensityImageFilter <OutputImageType, InputImageType> RescaleFilterOutType;
    typename RescaleFilterOutType::Pointer castFilterOut = RescaleFilterOutType::New();

    // In the same way, once the image is filtered, we need to convert it again to
    // VTK format to give it to CamiTK.
    typedef itk::ImageToVTKImageFilter<OutputImageType> itkToVtkFilterType;
    typename itkToVtkFilterType::Pointer itkToVtkFilter = itkToVtkFilterType::New();

    typedef itk::ImageToVTKImageFilter<InputImageType> itkToVtkFilterType2;
    typename itkToVtkFilterType2::Pointer itkToVtkFilter2 = itkToVtkFilterType2::New();

    // To update CamiTK progress bar while filtering, add an ITK observer to the filters.
    ItkProgressObserver::Pointer observer = ItkProgressObserver::New();
    // ITK observers generally give values between 0 and 1, and CamiTK progress bar
    //    wants values between 0 and 100...
    observer->SetCoef(100.0);

    // --------------------- Plug filters and parameters ---------------------------
    // From VTK to ITK
    vtkToItkFilter->SetInput(img);
    vtkToItkFilter->Update();

    // From original type to double type
    castFilterIn->SetInput(vtkToItkFilter->GetOutput());
    castFilterIn->AddObserver(itk::ProgressEvent(), observer);

    castFilterIn->Update();
    observer->Reset();

    // Apply Sobel Edge Detection Filter
    sobelFilter->SetInput(castFilterIn->GetOutput());
    sobelFilter->AddObserver(itk::ProgressEvent(), observer);

    sobelFilter->Update();
    observer->Reset();

    if (keepOrgVoxelType)  {
        castFilterOut->SetInput(sobelFilter->GetOutput());
        castFilterOut->AddObserver(itk::ProgressEvent(), observer);
        castFilterOut->Update();
        observer->Reset();
        itkToVtkFilter2->SetInput(castFilterOut->GetOutput());
        itkToVtkFilter2->AddObserver(itk::ProgressEvent(), observer);
        // --------------------- Actually execute all filters parts --------------------
        itkToVtkFilter2->Update();
        observer->Reset();

        resultImage = itkToVtkFilter2->GetOutput();
    }
    else {
        // From ITK to VTK
        itkToVtkFilter->SetInput(sobelFilter->GetOutput());
        itkToVtkFilter->AddObserver(itk::ProgressEvent(), observer);
        // --------------------- Actually execute all filters parts --------------------
        itkToVtkFilter->Update();
        observer->Reset();

        resultImage = itkToVtkFilter->GetOutput();
    }

    // --------------------- Create and return a copy (the filters will be deleted)--

    int extent[6];
    resultImage->GetExtent(extent);
    result->SetExtent(extent);
    result->DeepCopy(resultImage);

    // Set CamiTK progress bar back to zero (the processing filter is over)
    observer->Reset();


    return result;
}

