#include <comdef.h>
#include <string.h>
#include "tci.h"
#include "qsee_services.h"
#include "qsee_timer.h"
#include "qsee_heap.h"

#include "dashboard.h"

#include "TZ_Vendor_tl.h"
#include "process_cmd.h"

#define TAG "ARCOUNTER: "

/**
 * Modify the app name to your specific app name
 */
char TZ_APP_NAME[] = {"arcounter"};

tl_arcounter_ctx_t g_tl_arcounter_ctx;
/**
  @brief
    Add any app specific initialization code here
    QSEE will call this function after secure app is loaded and
    authenticated
*/
// Regular tz_app_init will be called inside scrypto library
// tz_app_init_ex will be called for initialisation from scrypto library
void tz_app_init_ex(void)
{
  /*  App specific initialization code*/
 // log_init(SEC_LOG_START, SEC_LOG_SIZE);
 // log_init(DEBUG_LOG_START, DEBUG_LOG_SIZE);

  qsee_log(QSEE_LOG_MSG_ERROR, "ARCOUNTER Init ex ");
}


void tz_app_cmd_handler(void* cmd, uint32 cmdlen,
                        void* resp, uint32 rsplen)
{
	uint32_t ret;
	uint32_t commandId;

	tciMessage_t *sendmsg = NULL;
	tciMessage_t *respmsg = NULL;

	if ((NULL == cmd) || (NULL == resp)) {
		qsee_log(QSEE_LOG_MSG_ERROR,
			 "tz_app_cmd_handler invalid input");
		return;
	}

	if (cmdlen < sizeof(tciMessage_t)) {
		qsee_log(QSEE_LOG_MSG_ERROR,
			 "cmdlen = %u < %u = sizeof(tciMessage_t)",
			 cmdlen, sizeof(tciMessage_t));
		return;
	}

	if (rsplen < sizeof(tciMessage_t)) {
		qsee_log(QSEE_LOG_MSG_ERROR,
			 "rsplen = %u < %u = sizeof(tciMessage_t)",
			 rsplen, sizeof(tciMessage_t));
		return;
	}

	sendmsg = (tciMessage_t *)cmd;
	respmsg = (tciMessage_t *)resp;

	if (sendmsg->header.len > cmdlen) {
		qsee_log(QSEE_LOG_MSG_ERROR,
			 "sendmsg->header.len = %u > %u = cmdlen",
			 sendmsg->header.len, cmdlen);
	}

	commandId = sendmsg->header.id;

	ret = process_cmd(&g_tl_arcounter_ctx, commandId, sendmsg, respmsg);

	respmsg->header.id = RSP_ID(commandId);
	respmsg->header.status = ret;

	qsee_log(QSEE_LOG_MSG_DEBUG, "sendmsg->header.id = 0x%08x",
		 sendmsg->header.id);
	qsee_log(QSEE_LOG_MSG_DEBUG, "respmsg->header.id = 0x%08x",
		 respmsg->header.id);
	qsee_log(QSEE_LOG_MSG_DEBUG, "respmsg->header.status = 0x%08x",
		 respmsg->header.status);
}

void exit_arcounter()
{
	return;
}

/**
  @brief
    App specific shutdown
    App will be given a chance to shutdown gracefully
*/
void tz_app_shutdown(void)
{
  exit_arcounter();
  /* app specific shutdown code*/
  qsee_log(QSEE_LOG_MSG_DEBUG, "ARCOUNTER shutdown");
  return;
}
