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

// CamiTK includes
#include "CannyEdgeDetection.h"

#include <Application.h>
#include <Property.h>

// ITK includes
#include <ItkProgressObserver.h>
#include <itkImageToVTKImageFilter.h>
#include <itkVTKImageToImageFilter.h>
#include <itkCastImageFilter.h>
#include <itkRescaleIntensityImageFilter.h>
#include <itkCannyEdgeDetectionImageFilter.h>

using namespace camitk;


// --------------- constructor -------------------
CannyEdgeDetection::CannyEdgeDetection(ActionExtension* extension) : Action(extension) {
    // Setting name, description and input component
    setName("Canny Edge Detection");
    setDescription("<br>The <b> <i>Canny edge detector</i> </b> is an edge detection operator that uses a multi-stage algorithm to detect a wide range of edges in images. <br> \n The filter steps are : \n  * Preprocessing noise reduction using a gaussian convolution filtering. \n  * Finding the intensity gradient of the image \n  * Non-maximum suppression \n  * Tracing edges through the image and hysteresis thresholding \n It was developed by John F. Canny in 1986. <i>(source: Wikipedia)</i>.<br> \n This filter is widely used for edge detection since it is the optimal solution satisfying the constraints of good sensitivity, localization and noise robustness. <i>(source: ITK Developer's Guide)</i>.<br>  ");

    setComponentClassName("ImageComponent");

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

    // Setting parameters default values
    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);

    Property* varianceProperty = new Property(tr("Variance"), 2.0, tr("The variance is used in the gaussian preprocessing step. \nThe higher the variance is, the less the edges detection will be noise sensitive."), "");
    varianceProperty->setAttribute("minimum", 0);
    varianceProperty->setAttribute("maximum", 100);
    varianceProperty->setAttribute("singleStep", 0.05);
    addParameter(varianceProperty);

    Property* upperThresholdProperty = new Property(tr("Upper threshold"), 0.0, tr("The upper threshold is used at step 3 to determine whether a voxel belongs an edge or not. \nAbove, the voxel is detected as an edge.\nBelow and upper the low threshold, the voxel is accepted if it is connected to an edge voxel neighbor."), "");
    upperThresholdProperty->setAttribute("singleStep", 0.1);
    addParameter(upperThresholdProperty);

    Property* lowerThresholdProperty = new Property(tr("Lower threshold"), 0.0, tr("The lower threshold is used at step 3 to determine whether a voxel belongs an edge or not. \nAbove, and under the upper threshold the voxel is detected as an edge if it is connected to an edge voxel neighbor. \nBelow, the voxel is rejected."), "");
    lowerThresholdProperty->setAttribute("singleStep", 0.1);
    addParameter(lowerThresholdProperty);
}

// --------------- destructor -------------------
CannyEdgeDetection::~CannyEdgeDetection() {
    // do not delete the widget has it might have been used in the ActionViewer (i.e. the ownership might have been taken by the stacked widget)
}

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

void CannyEdgeDetection::process(ImageComponent* comp) {
    // Get the parameters
    this->keepOrgVoxelType = property("Keep original voxel type?").toBool();
    this->variance = property("Variance").toDouble();
    this->upperThreshold = property("Upper threshold").toDouble();
    this->lowerThreshold = property("Lower threshold").toDouble();
    // ITK filter implementation using templates
    vtkSmartPointer<vtkImageData> inputImage = comp->getImageData();
    vtkSmartPointer<vtkImageData> outputImage = implementProcess(inputImage);
    ImageComponent* outputComp = new ImageComponent(outputImage, comp->getName() + "_edges");

    // consider frame policy on new image created
    Action::applyTargetPosition(comp, outputComp);

    Application::refresh();
}

#include "CannyEdgeDetection.impl"

// ITK filter implementation
template <class InputPixelType, class OutputPixelType, const int dim>
vtkSmartPointer<vtkImageData> CannyEdgeDetection::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> CastFilterType;
    typename CastFilterType::Pointer toDoubleFilter = CastFilterType::New();

    typedef itk::CannyEdgeDetectionImageFilter<OutputImageType, OutputImageType> CannyFilterType;
    typename CannyFilterType::Pointer cannyFilter = CannyFilterType::New();

    typedef itk::RescaleIntensityImageFilter<OutputImageType, InputImageType> ToOrgFilterType;
    typename ToOrgFilterType::Pointer toOrgFilter = ToOrgFilterType::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();
// ------------------------- WRITE YOUR CODE HERE ----------------------------------

    // 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->AddObserver(itk::ProgressEvent(), observer);
    vtkToItkFilter->Update();
    observer->Reset();

    toDoubleFilter->SetInput(vtkToItkFilter->GetOutput());
    toDoubleFilter->AddObserver(itk::ProgressEvent(), observer);
    toDoubleFilter->Update();
    observer->Reset();

    cannyFilter->SetInput(toDoubleFilter->GetOutput());
    cannyFilter->SetVariance(variance);
    cannyFilter->SetUpperThreshold(upperThreshold);
    cannyFilter->SetLowerThreshold(lowerThreshold);

    cannyFilter->AddObserver(itk::ProgressEvent(), observer);
    cannyFilter->Update();
    observer->Reset();

    if (keepOrgVoxelType)  {
        toOrgFilter->SetInput(cannyFilter->GetOutput());
        toOrgFilter->AddObserver(itk::ProgressEvent(), observer);
        toOrgFilter->Update();
        observer->Reset();

        // From ITK to VTK
        itkToVtkFilter2->SetInput(toOrgFilter->GetOutput());
        itkToVtkFilter2->AddObserver(itk::ProgressEvent(), observer);
        itkToVtkFilter2->Update();
        observer->Reset();
        // --------------------- Create and return a copy (the filters will be deleted)--
        resultImage = itkToVtkFilter2->GetOutput();
    }
    else {
        // From ITK to VTK
        itkToVtkFilter->SetInput(cannyFilter->GetOutput());
        itkToVtkFilter->AddObserver(itk::ProgressEvent(), observer);
        itkToVtkFilter->Update();
        observer->Reset();
        // --------------------- Create and return a copy (the filters will be deleted)--
        resultImage = itkToVtkFilter->GetOutput();
    }

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

