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

  Program:   Visualization Toolkit
  Module:    vtkReactiveCommandHelper.h

  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.

=========================================================================*/
/**
 * @class   vtkReactiveCommandHelper
 * @brief   A helper for rxvtk::from_event
 *
 * vtkReactiveCommandHelper wraps rxvtk::from_event  into a vtk class which
 * enables vtk wrapping infastructure to generate python bindings. Moreover,
 * observables created with this class terminate if the helpers is destroyed or
 * Unsubscribe is called.
 *
 *
 * @sa vtkReactiveCommand
 */

#ifndef vtkReactiveCommandHelper_h
#define vtkReactiveCommandHelper_h
#include "vtkRemotingPythonAsyncCoreModule.h"

#include "vtkObject.h"

#include "vtk_rxcpp.h"
// clang-format off
#include VTK_REMOTING_RXCPP(rx.hpp)
// clang-format on

class VTKREMOTINGPYTHONASYNCCORE_EXPORT vtkReactiveCommandHelper : public vtkObject
{
public:
  static vtkReactiveCommandHelper* New();
  vtkTypeMacro(vtkReactiveCommandHelper, vtkObject);
  void PrintSelf(ostream& os, vtkIndent indent) override;

  using ObservedType = std::tuple<vtkObject*, unsigned long, void*>;

  //@{
  /** Get an observable that fires each time `eventId` is emmited from `object`
   *
   * The return value is a cold observable i.e. it does not start emitting
   * values until something subscribes to it.
   *
   * @section Triggers Triggers
   *
   * * on_next: every time eventId is emmited from object
   *
   * * on_error: never
   *
   * * on_completed: when this instance is destroyed or if the associated
   *   object is destroyed `object` or finally, if Unsubscribe() is called.
   */
  rxcpp::observable<ObservedType> GetObservable();
#ifdef __WRAP__
  vtkPythonObservableWrapper<std::tuple<vtkObject*, unsigned long, void*>> GetObservable();
#endif
  //@}

  /** Emit a completion signal to all observables created through
   * `GetObservable()`. This will cause * all the subscriptions to complete. In
   * Python API all async iterators will also complete.
   */
  void Unsubscribe();

  void SetObject(vtkObject* object);
  void SetEventId(unsigned long int eventId);

protected:
  vtkReactiveCommandHelper();
  ~vtkReactiveCommandHelper() override;

private:
  vtkReactiveCommandHelper(const vtkReactiveCommandHelper&) = delete;
  void operator=(const vtkReactiveCommandHelper&) = delete;

  vtkObject* Object;
  unsigned long EventId;

  std::vector<rxcpp::subscriber<ObservedType>> Subscribers;
};

#endif
