// SaxonApiException.cpp : Defines the exported functions for the DLL
// application.
//

#include "saxonc/SaxonApiException.h"

#ifdef MEM_DEBUG
#define new new (__FILE__, __LINE__)
#endif

#ifdef _LIBCPP___EXCEPTION_EXCEPTION_H
char const* SaxonApiException::what() const _NOEXCEPT
{
  // need cast to remove const flag
  SaxonApiException *s = const_cast<SaxonApiException*>(this);
  return s->getMessageWithErrorCode();
}
#else

const char *SaxonApiException::what() {
  return this->getMessageWithErrorCode();
}
#endif


SaxonApiException::SaxonApiException(bool staticError) {
  message = "";
  lineNumber = -1;
  errorCode = "";
  systemId = "";
  isStaticError = staticError;
  
  // preload the error message
  getMessageWithErrorCode();
}

SaxonApiException::SaxonApiException(const SaxonApiException &ex) {
  message = ex.message;
  lineNumber = ex.lineNumber;
  errorCode = ex.errorCode;
  systemId = ex.systemId;
  isStaticError = ex.isStaticError;
}

SaxonApiException::SaxonApiException(const char *m) {
  if (m != nullptr) {
    message = std::string(m);
  } else {
    message = "unknown exception";
  }

  lineNumber = -1;
  errorCode = "";
  systemId = "";
  isStaticError = false;
}

SaxonApiException::SaxonApiException(const char *m, const char *ec,
                                     const char *sysId, int linenumber){
  if (m != nullptr) {
    message = std::string(m);
  } else {
    message = "";
  }

  lineNumber = linenumber;

  if (ec != nullptr) {
    errorCode = std::string(ec);
  } else {
    errorCode = "";
  }

 ec_message = errorCode + " " + message;

  if (sysId != nullptr) {
    systemId = std::string(sysId);
  } else {
    systemId = "";
  }
  isStaticError = false;
}


SaxonApiException::SaxonApiException(saxon_status_t status, const char *m, const char *ec,
                                     const char *sysId, int linenumber, int numErrors): SaxonApiException(m, ec, sysId, linenumber)  {

  exception_status = status;
  isStaticError = false;
  numOfErrors = numErrors;
}


SaxonApiException::SaxonApiException(saxon_error_t r): SaxonApiException(r.status, r.message, r.error_code, r.system_id,r.line_number,r.num_of_errors) {}

SaxonApiException::~SaxonApiException() throw() {
  if (!message.empty()) {
    message.clear();
  }
  if (!s_message.empty()) {
    s_message.clear();
  }
  if (!ec_message.empty()) {
    ec_message.clear();
  }
  if (!errorCode.empty()) {
    errorCode.clear();
  }
  if (!systemId.empty()) {
    systemId.clear();
  }
}

const char *SaxonApiException::getErrorCode() {
  return errorCode.c_str();
}

int SaxonApiException::getLineNumber() {
  return lineNumber;
}

const char *SaxonApiException::getSystemId() {
  return systemId.c_str();
}

const char *SaxonApiException::getMessage() {
  return message.c_str();
}

const char *SaxonApiException::getMessageWithErrorCode() {
    return ec_message.c_str();
}

int SaxonApiException::staticErrorCount() {
    return numOfErrors;
}
