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

  Program:   ParaView
  Module:    vtkPythonContextHelper.cxx

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.paraview.org/HTML/Copyright.html 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 "vtkPythonContextHelper.h"

#include "vtkImageData.h"
#include "vtkLogger.h"
#include "vtkObjectFactory.h"
#include "vtkPythonRunLoop.h"
#include "vtkPythonUtil.h"
#include "vtkSMProxy.h"
#include "vtkSMViewProxy.h"
#include "vtkSmartPyObject.h"

#include "vtkPythonAsyncCoreUtilities.txx"

class vtkPythonContextHelper::vtkInternals
{
public:
  vtkSMProxy* Proxy;
  rxcpp::composite_subscription subscription;
};

vtkStandardNewMacro(vtkPythonContextHelper);

//----------------------------------------------------------------------------
vtkPythonContextHelper::vtkPythonContextHelper()
  : Internals(new vtkPythonContextHelper::vtkInternals)
{
}

//----------------------------------------------------------------------------
vtkPythonContextHelper::~vtkPythonContextHelper() = default;

//----------------------------------------------------------------------------
void vtkPythonContextHelper::SetProxy(vtkSMProxy* proxy)
{
  this->Internals->Proxy = proxy;
}
//----------------------------------------------------------------------------
void vtkPythonContextHelper::Unsubscribe()
{
  this->Internals->subscription.unsubscribe();
}

//----------------------------------------------------------------------------
PyObject* vtkPythonContextHelper::NewIterator()
{
  vtkSmartPyObject iterator = nullptr;
  if (auto* proxy = vtkSMViewProxy::SafeDownCast(this->Internals->Proxy))
  {
    iterator = vtkPythonRunLoop::GetInstance()->CreateAsyncIterator();
    proxy->GetImageObservable().subscribe(
      this->Internals->subscription,

      // on_next
      [iterator](auto value) {
        vtkLogF(INFO, "PUSH");
        vtkPythonScopeGilEnsurer gilEnsurer;
        PyObject* queue = PyObject_CallMethod(iterator, "get_queue", "");
        if (queue == nullptr)
        {
          CheckAndClearError();
          throw std::runtime_error("error getting iterator's queue");
        }
        PushToQueue(queue, value);
      },

      // on_error
      [iterator](std::exception_ptr eptr) {
        vtkLogF(INFO, "ERROR");
        try
        {
          std::rethrow_exception(eptr);
        }
        catch (const std::exception& e)
        {
          vtkPythonScopeGilEnsurer gilEnsurer;

          // in python we would have a try: except StopIterator
          PyObject* future = PyObject_CallMethod(iterator, "get_future", "");
          SetFutureException(future, e.what());
        }
      },

      // on_completed
      [iterator]() {
        vtkLogF(INFO, "COMPLETED");
        vtkPythonScopeGilEnsurer gilEnsurer;

        // in python we would have a try: except StopIterator
        PyObject* future = PyObject_CallMethod(iterator, "get_future", "");

        PyObject* exception = PyErr_Occurred();
        if (exception == nullptr)
        {
          SetFutureValue(future, true);
        }
        // iterator already destroyed on python side
        else if (PyErr_GivenExceptionMatches(exception, PyExc_StopIteration))
        {
          PyErr_Clear();
          return;
        }
        else
        {
          PyErr_Print();
        }
      }

    );
  }
  return iterator;
}

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