#include <BinBin.h>
#include <BinBinInt.h>

uint32 Jnh_CPGetContext(CPContext & context) {
  context.val = 0;
  return Bin_LockCP();
}

uint32 Jnh_CPGetFirstCert(CPContext & context, 
                          x509_certificate ** cert) {
  context.val = 0;
  return Jnh_CPGetNextCert(context, cert);
}

uint32 Jnh_CPGetNextCert(CPContext & context, 
                         x509_certificate ** cert) {
  int certs;
  *cert = NULL;
  certs = certPool.get_child_count();
  if (certs <= context.val) return BIN_NO_MORE_CERTS;
  *cert = certPool[context.val];
  context.val++;
  return 0;
}

uint32 Jnh_CPReleaseContext(CPContext & context) {
  context.val = -1;
  return Bin_UnlockCP();
}

uint32 Jnh_CPAddCert(const x509_certificate * cert) {
  buffer_t buffer;
  uint32 status;
  x509_certificate * new_child;

  status = cert->write(buffer);
  if (status) return status;
  Bin_LockCP();
  new_child = certPool.add_child();
  status = new_child->read(buffer);
  Bin_UnlockCP();
  return status;
}
