/**
 * \file BGDNetConnection.cpp
 * \brief Реализация класса Connection
 */

#include "BGDNetPch.h"

#include "BGDNetConnection.h"

#include <nwerror.h>

namespace BGDNet
{

const NWCONN_HANDLE Connection::s_invalidHandle = -1;
  
Connection::Connection( ConnRef ref, bool licenseFlag )
  throw(Exception)
{
  open(ref, licenseFlag);
}

Connection::Connection( const char* srvName, bool licenseFlag )
  throw(Exception)
{
  open(srvName, licenseFlag);
}

Connection::~Connection( void )
{
  close();
}

void Connection::open( ConnRef ref, bool licenseFlag )
  throw(Exception)
{
  close();
  NWRCODE err = NWCCOpenConnByRef(
    ref,
    licenseFlag ? NWCC_OPEN_LICENSED : NWCC_OPEN_UNLICENSED,
    NWCC_RESERVED,
    &m_connHandle);
  if (SUCCESS != err)
  {
    m_connHandle = s_invalidHandle;
    throw Exception(err);
  }
}

void Connection::open( const char* srvName, bool licenseFlag )
  throw(Exception)
{
  close();
  NWRCODE err = NWCCOpenConnByName(
    0,
    srvName,
    NWCC_NAME_FORMAT_BIND,
    licenseFlag ? NWCC_OPEN_LICENSED : NWCC_OPEN_UNLICENSED,
    NWCC_TRAN_TYPE_WILD,
    &m_connHandle);
  if (SUCCESS != err)
  {
    m_connHandle = s_invalidHandle;
    throw Exception(err);
  }
}

void Connection::close( void )
{
  if (s_invalidHandle != m_connHandle)
  {
    NWCCCloseConn(m_connHandle);
    m_connHandle = s_invalidHandle;
  }
}

ConnRef Connection::ref( void ) const
  throw(Exception)
{
  nuint32 r;
  NWRCODE err = NWCCGetConnRef(m_connHandle, &r);
  if (SUCCESS != err)
    throw Exception(err);
  return ConnRef(r);
}

Connection::operator NWCONN_HANDLE( void ) const
{
  return m_connHandle;
}

} // namespace BGDNet
