#include <tee_internal_api.h>
#include <qsee_timer.h>
#include <comdef.h>
#include <qsee_services.h>
#include <tees_log.h>
#include <protocol.h>

extern PersObjectCmd g_po_cmd_buffer;
extern uint32_t g_listener_id;

static TEE_Result GetReeTime(TEE_Time *time) {
  TEE_Result status = TEE_ERROR_BAD_PARAMETERS;

  if (g_listener_id == 0) {
    return TEE_ERROR_NOT_SUPPORTED;
  }

  TEE_MemFill(&g_po_cmd_buffer, 0x00, sizeof(g_po_cmd_buffer));
  g_po_cmd_buffer.cmd_id = PROTOCOL_COMMAND_GETREETIME;
  g_po_cmd_buffer.data_len = sizeof(TEE_Time);
  qsee_request_service(g_listener_id,
                       &g_po_cmd_buffer, sizeof(g_po_cmd_buffer),
                       &g_po_cmd_buffer, sizeof(g_po_cmd_buffer));
  status = g_po_cmd_buffer.cmd_id;

  if (TEE_SUCCESS == status) {
    TEE_MemMove(time, &g_po_cmd_buffer.data, min(sizeof(TEE_Time),
                                                 g_po_cmd_buffer.data_len));
  }
  return status;
}

void TEE_GetREETime(TEE_Time *time) {
  if (!time) {
    return;
  }
  if (TEE_SUCCESS != GetReeTime(time)) {
    MB_LOGE("Panic reason: Get NWD Time error\n");
    TEE_Panic(0);
  }
}

// similar implementation for all platformes
TEE_Result TEE_Wait(uint32_t timeout) {
  unsigned long long current_msec = 0;
  unsigned long long start_msec = 0;

  if (!timeout) {
    return TEE_SUCCESS;
  }
  start_msec = qsee_get_uptime();
  do {
    if (TEE_GetCancellationFlag()) {
      MB_LOGW("TEE_Wait got cancellation\n");
      return TEE_ERROR_CANCEL;
    }
    current_msec = qsee_get_uptime();
  } while (current_msec - start_msec < (unsigned long long)timeout);
  return TEE_SUCCESS;
}
