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

  Program:   ParaView
  Module:    vtkZeroMQController.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 "vtkZeroMQController.h"

#include "vtkObjectFactory.h"
#include "vtkZeroMQCommunicator.h"
#include "vtkNew.h"
#include <zmq.hpp>

namespace
{
  // All API on this class must be thread-safe!
  class ZeroMQInfo
    {
    zmq::context_t ZMQContext;
  public:
    ZeroMQInfo() : ZMQContext(0)
      {
      }
    ~ZeroMQInfo()
      {
      cout << "Context being destroyed!!!" << endl;
      }

    zmq::context_t& GetContext()
      {
      return this->ZMQContext;
      }
    };
  static ZeroMQInfo ZeroMQ;
}

int vtkZeroMQController::Initialized = 0;

vtkStandardNewMacro(vtkZeroMQController);
//----------------------------------------------------------------------------
vtkZeroMQController::vtkZeroMQController()
{
}

//----------------------------------------------------------------------------
vtkZeroMQController::~vtkZeroMQController()
{
  if (this->Communicator)
    {
    this->Communicator->Delete();
    this->Communicator = NULL;
    }
  this->RMICommunicator = NULL;
}

//----------------------------------------------------------------------------
void vtkZeroMQController::Initialize(int* , char***)
{
  ZeroMQ.GetContext();
  vtkZeroMQController::Initialized++;
}


//----------------------------------------------------------------------------
bool vtkZeroMQController::Connect(const char* url)
{
  assert(this->Communicator == NULL);
  vtkNew<vtkZeroMQCommunicator> comm;
  comm->SetContext(&ZeroMQ.GetContext());
  if (comm->Connect(url))
    {
    this->Communicator = comm.GetPointer();
    this->Communicator->Register(this);
    this->RMICommunicator = this->Communicator;
    return true;
    }
  return false;
}

//----------------------------------------------------------------------------
bool vtkZeroMQController::Bind(const char* url)
{
  assert(this->Communicator == NULL);
  vtkNew<vtkZeroMQCommunicator> comm;
  comm->SetContext(&ZeroMQ.GetContext());
  if (comm->Bind(url))
    {
    this->Communicator = comm.GetPointer();
    this->Communicator->Register(this);
    this->RMICommunicator = this->Communicator;
    return true;
    }
  return false;
}

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