/*
@file app_main.c
@brief App main entry point.
*/

#include <comdef.h>
//#include <rt_misc.h>
#include <string.h>
#include "qsee_log.h"
#include "qsee_heap.h"
#include "qsee_comstr.h"
#include "qsee_services.h"
#include "qsee_kdf.h"
#include "authhat_protocol.h"
//#include "km_get_auth_token_key.h"

void qsee_log_wrapper(UINT8 pri, const char * format, ...)
{
    /* force 'pri' to use QSEE_LOG_MSG_ERROR or QSEE_LOG_MSG_FATAL
     * 
     * Starting from TZ.BF.4.0.1-00088-M8996AAAAANAZT TZBSP, your TZ app needs to call 'qsee_log_set_mask()' with preferred bit masks for qsee logging except for qsee logs with 'QSEE_LOG_MSG_ERROR | QSEE_LOG_MSG_FATAL' bit masks.
     * Namely, please try to call this QSEE API first if you need to see qsee logs with QSEE_LOG_MSG_DEBUG bit mask additionally.
     * qsee_log_set_mask(QSEE_LOG_MSG_DEBUG);
     */
    qsee_log(QSEE_LOG_MSG_ERROR, format);
    return;
}

fpTZ_LOG LOG_MSG = &qsee_log_wrapper;
//fpTZ_LOG LOG_MSG = &qsee_log;

/** 
 * app name
 */

char TZ_APP_NAME[] = {"authhat"};

/**
  @brief 
    Add any app specific initialization code here
    QSEE will call this function after secure app is loaded and
    authenticated
*/
void tz_app_init(void)
{
    int retval=0;
    /*  App specific initialization code*/  
    (*LOG_MSG)(QSEE_LOG_MSG_ERROR, "%s Init", TZ_APP_NAME);

}

/**
  @brief 
    App specific commands should be handled in this
    function

  @param[in]      cmd         Requested command structure
  @param[in]      cmdlen      length of request commad struct
  @param[in/out]  rsp         Resposnse structure
  @param[in/out]  rsplen      length of response commad struct
*/
void tz_app_cmd_handler(void* cmd, int cmdlen, 
                        void* rsp, int rsplen)
{

    /* Request-response buffers are allocated by non-secure side*/
    /* Add code to process requests and set response (if any)*/

    cmd_req_t *cmd_req = (cmd_req_t *)cmd;

    if ((cmd == NULL) || (rsp == NULL) || !cmdlen || !rsplen) {
        (*LOG_MSG)(QSEE_LOG_MSG_ERROR, "cmd=%x, cmdlen=%d, rsp=%x, rsplen=%d\n", cmd, cmdlen, rsp, rsplen);
        return;
    }

    (*LOG_MSG)(QSEE_LOG_MSG_ERROR, "##############################");
    (*LOG_MSG)(QSEE_LOG_MSG_ERROR, "AUTHHAT TZ App cmd handler, cmd_id = %d START", cmd_req->cmd_id);

    tl_cmd_handler(cmd, cmdlen, rsp, rsplen);

    (*LOG_MSG)(QSEE_LOG_MSG_ERROR, "##############################");
}

/**
  @brief 
    App specific shutdown code
    App will be given a chance to shutdown gracefully
*/
void tz_app_shutdown(void)
{
    /* app specific shutdown code*/
    (*LOG_MSG)(QSEE_LOG_MSG_ERROR, "%s shutdown", TZ_APP_NAME);
    return;
}

