//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2015 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
// 
#include "VTKProgress.hpp"
#include <vtkAlgorithm.h>
#include <vtkCallbackCommand.h>

namespace mgx {
namespace process {

static void startCallback(vtkObject*, unsigned long, void* clientdata, void*)
{
  Progress* progress = (Progress*)clientdata;
  progress->advance(0);
}

static void progressCallback(vtkObject*, unsigned long, void* clientdata, void* calldata)
{
  Progress* progress = (Progress*)clientdata;
  double value = *(double*)calldata;
  progress->advance(int(100 * value));
}

static void endCallback(vtkObject*, unsigned long, void* clientdata, void*)
{
  Progress* progress = (Progress*)clientdata;
  progress->advance(100);
}

VTKProgress::VTKProgress(const QString& text)
  : progress()
  , progressHandler(0)
  , startHandler(0)
  , endHandler(0)
{
  progress.start(text, 100, false);
  startHandler = vtkCallbackCommand::New();
  startHandler->SetClientData(&progress);
  startHandler->SetCallback(startCallback);
  endHandler = vtkCallbackCommand::New();
  endHandler->SetClientData(&progress);
  endHandler->SetCallback(endCallback);
  progressHandler = vtkCallbackCommand::New();
  progressHandler->SetClientData(&progress);
  progressHandler->SetCallback(progressCallback);
}

VTKProgress::~VTKProgress()
{
  progressHandler->Delete();
  startHandler->Delete();
  endHandler->Delete();
}

void VTKProgress::setFilter(vtkAlgorithm* filter)
{
  filter->AddObserver(vtkCommand::StartEvent, startHandler);
  filter->AddObserver(vtkCommand::ProgressEvent, progressHandler);
  filter->AddObserver(vtkCommand::EndEvent, endHandler);
}
}
}
