/*
 * AXFRingBufInternal.hpp
 */

#include "AXFRingBufInternal.hpp"
#include "AXFConditionVariableInternal.hpp"

AXFRingBufInternal::AXFRingBufInternal(
  char* buf,
  int size,
  AXFMutex* mutex_r,
  AXFMutex* mutex_w,
  AXFConditionVariableInternal* cond_r,
  AXFConditionVariableInternal* cond_w)
  : AXCRingBuf(buf, size) {

  m_mutex[RINGBUF_READ] = mutex_r;
  m_mutex[RINGBUF_WRITE] = mutex_w;
  m_cond[RINGBUF_READ] = cond_r;
  m_cond[RINGBUF_WRITE] = cond_w;
}

AXFRingBufInternal::~AXFRingBufInternal() {
    delete m_mutex[RINGBUF_READ];
    delete m_mutex[RINGBUF_WRITE];
    delete m_cond[RINGBUF_READ];
    delete m_cond[RINGBUF_WRITE];
}

AXFRingBufInternal::ringBufStatus AXFRingBufInternal::init() {
  if (AXCRingBuf::init() != RINGBUF_SUCCESS) return RINGBUF_ERROR;

  for (int i=0; i<RINGBUF_RW_NUM; i++) {
    ringBufRW rw = (ringBufRW)i;
    if (m_mutex[rw]) {
      if (m_mutex[rw]->init() != AXFMutex::MUTEX_SUCCESS) return RINGBUF_ERROR;
    }
    if (m_cond[rw]) {
      if (m_cond[rw]->init() != AXFConditionVariableInternal::COND_SUCCESS) return RINGBUF_ERROR;
    }
  }
  return RINGBUF_SUCCESS;
}

AXFRingBufInternal::ringBufStatus AXFRingBufInternal::lock(ringBufRW rw) {
  if (m_mutex[rw]) {
    if (m_mutex[rw]->lock() != AXFMutex::MUTEX_SUCCESS) return RINGBUF_ERROR;
  }
  return RINGBUF_SUCCESS;
}

AXFRingBufInternal::ringBufStatus AXFRingBufInternal::unlock(ringBufRW rw) {
  if (m_mutex[rw]) {
    if (m_mutex[rw]->unlock() != AXFMutex::MUTEX_SUCCESS) return RINGBUF_ERROR;
  }
  return RINGBUF_SUCCESS;
}

AXFRingBufInternal::ringBufStatus AXFRingBufInternal::waitFor(ringBufRW rw) {
  if (m_cond[rw]) {
    if (m_cond[rw]->wait() != AXFConditionVariableInternal::COND_SUCCESS) return RINGBUF_ERROR;
  }
  return RINGBUF_SUCCESS;
}

AXFRingBufInternal::ringBufStatus AXFRingBufInternal::signalTo(ringBufRW rw) {
  if (m_cond[rw]) {
    if (m_cond[rw]->signal() != AXFConditionVariableInternal::COND_SUCCESS) return RINGBUF_ERROR;
  }
  return RINGBUF_SUCCESS;
}
