/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkReactiveCommandHelper.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkReactiveCommandHelper.h"
#include "vtkObjectFactory.h"
#include "vtkReactiveCommand.h"

vtkStandardNewMacro(vtkReactiveCommandHelper);
//------------------------------------------------------------------------------
vtkReactiveCommandHelper::vtkReactiveCommandHelper() = default;

//------------------------------------------------------------------------------
vtkReactiveCommandHelper::~vtkReactiveCommandHelper()
{
  this->Unsubscribe();
}

//------------------------------------------------------------------------------
void vtkReactiveCommandHelper::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//------------------------------------------------------------------------------
void vtkReactiveCommandHelper::SetObject(vtkObject* object)
{
  this->Object = object;
}

//------------------------------------------------------------------------------
void vtkReactiveCommandHelper::SetEventId(unsigned long eventId)
{
  this->EventId = eventId;
}

//------------------------------------------------------------------------------
void vtkReactiveCommandHelper::Unsubscribe()
{
  for (auto& subscriber : this->Subscribers)
  {
    subscriber.on_completed();
  }

  this->Subscribers.clear();
}

//------------------------------------------------------------------------------
rxcpp::observable<vtkReactiveCommandHelper::ObservedType> vtkReactiveCommandHelper::GetObservable()
{
  auto observable = rxcpp::observable<>::create<ObservedType>(
    [this](const rxcpp::subscriber<ObservedType>& subscriber) {
      // setup subscription
      rxvtk::from_event(this->Object, this->EventId).subscribe(subscriber);
      // keep track of them so we can Unsubscribe
      this->Subscribers.push_back(subscriber);
    });
  return observable;
}
