#ifdef UNIX
# include <malloc.h>
#endif
#include "vxUtils.h" 
#include "IviewControlMonitor.h"

IviewControlMonitor::IviewControlMonitor(const char *controlName)
{
  char errorBuf[errorMsgSize];
  MBool found = FALSE;
  IviewRequest request;
  _controlName = strdup(controlName);
  
  for (unsigned index = 0; index < MaxControlSources; index++)
  {
    _dmControlSource = new DmControlSource(index);
    MBool used;
    _dmControlSource->hasClient(&used);
    if (used)
    {
      _dmControlSource->setMonitorRole();
      
      if (_dmControlSource->readRequest(&request) != IviewSuccess)
      {
	_dmControlSource->errorMsg(errorBuf);
	setError(errorBuf);
	return;
      }
    }
    if (!strcmp(request.controlName, controlName))
    {
      found = TRUE;
      break;
    }

    delete _dmControlSource;
  }

  if (!found)
  {
    sprintf(errorBuf, "IviewControl \"%s\" not found", _controlName);
    setError(errorBuf);
    return;
  }
}


IviewControlMonitor::~IviewControlMonitor()
{
  free(_controlName);
}


int IviewControlMonitor::getDevices(unsigned short *deviceMask)
{
  char errorBuf[errorMsgSize];
  IviewRequest request;
  IviewMessage msg;
  
  MBool used;
  _dmControlSource->hasClient(&used);
  if (!used)
  {
    sprintf(errorBuf, "IviewControl \"%s\" has no client", _controlName);
    setError(errorBuf);
    return IviewNoClient;
  }
  int ret;

  if ((ret = _dmControlSource->readRequest(&request)) != IviewSuccess)
  {
    _dmControlSource->errorMsg(errorBuf);
    setError(errorBuf);
    return ret;
  }

  if ((ret = _dmControlSource->readMessage(&msg)) != IviewSuccess)
  {
    _dmControlSource->errorMsg(errorBuf);
    setError(errorBuf);
    return ret;
  }

  if (strcmp(_controlName, request.controlName))
  {
    sprintf(errorBuf, "Control changed to \"%s\"", request.controlName);
    setError(errorBuf);
    return IviewClientChanged;
  }

  *deviceMask = msg.deviceMask;
  return IviewSuccess;
}


