/*******************************************************************************
 * (c) Copyright 2015 Microsemi Corporation.  All rights reserved.
 *
 *
 *
 * SVN $Revision: $
 * SVN $Date: $
 */

#include "egl_assert.h"
#include <stdio.h>
#include <stdlib.h>

#include <errno.h>

#include "../../log/inc/egl_log.h"
#include "egl_types.h"

/* ----------------- Defines ---------------------- */
/* ----------------- Enumerations ---------------------- */
/* ----------------- Structs/Types ---------------------- */

/* ----------------- Static Data ---------------------- */

static const char* assertion_logName   = "ASSERT";
static uint16_t    assertion_logHandle = 0;


/*!
 *\brief
 *    Log the assert before exiting the process
 *
 *    <em>
 *    Prerequisite: Calling application must have invoked egl_assert_init() prior to any
 *    possible assert
 *    </em>
 *
 *\param[in]    file        name of file causing assert
 *\param[in]    function    name of function causing assert
 *\param[in]    line        line number of the assert
 *\param[in]    reasonCode  ReasonCode to log with assert
 *\param[in]    expression  The expression causing the assert
  */
void egl_assert_abort(const char* file,
                      const char* function,
                      const int   line,
                      const int   reasonCode,
                      const char* expression)
{
    if(assertion_logHandle != 0)
    {
#if 0 // TODO
        DO_LOG_ERROR(assertion_logHandle,
                  file,
                  function,
                  line,
                  "ASSERT FAILURE ERRNO: (%d)  Expr: (%s)  Value: (%d)  ",
                  errno,
                  expression,
                  reasonCode);
#endif
    }
	fprintf(stderr, 
                  "%s::%s() line %d: ASSERT FAILURE ERRNO: (%d)  Expr: (%s)  Value: (%d)\n",
                  file,
                  function,
                  line,
                  errno,
                  expression,
                  reasonCode); fflush(stderr);

#ifndef ASSERT_AND_CONTINUE
    abort();
#endif
} /* egl_assert_abort */



/*
 * See egl_assert.h for prototype description.
 *
 * Initilialise function to be invoked by application start-up
 *
 * 'Singleton' pattern that will actually only execute the initialisation
 *  once even if called multiple times.
 */
void egl_assert_init()
{
    static bool initialised = false;

    if(!initialised)
    {
        initialised = true;

        log_init();
        assertion_logHandle = log_register(assertion_logName);
        //log_setLevelError(assertion_logHandle);
        log_setLevelDebug(assertion_logHandle);
    }
}


