// Copyright (c) 2017, 2019, 2021 Qualcomm Technologies, Inc.  All Rights Reserved.
// Qualcomm Technologies Proprietary and Confidential.

#include <stddef.h>
#include <stdint.h>
#include "CAppLegacyTest_open.h"
#include "cdefs.h"
#include "IAppLegacyTest.h"
#include "IAppLegacyTest_invoke.h"
#include "object.h"
#include "qsee_heap.h"
#include "qsee_log.h"

extern int smplap_sfs_unit_open(void);

extern void tz_app_cmd_handler(void* cmd, uint32_t cmdlen,
                               void* rsp, uint32_t rsplen);

/*******************************************************************************
 * AppLegacyTest: Call the old tz_app_cmd_handler via a Mink object
 * ****************************************************************************/

/** This, i.e. a context with only refs inside, looks pointless, but we do it
 * so that we can monitor when we're actually released/deleted, and do something
 * at that time. In this case, we run a test case which calls a listener. */
typedef struct {
  int refs;
} CAppLegacyTest;

static int32_t CAppLegacyTest_retain(CAppLegacyTest *me)
{
  me->refs++;
  return Object_OK;
}

static int32_t CAppLegacyTest_release(CAppLegacyTest *me)
{
  if (--me->refs == 0) {
    smplap_sfs_unit_open();
    qsee_free(me);
  }
  return Object_OK;
}

static int32_t CAppLegacyTest_handleRequest(CAppLegacyTest* cxt,
                                            const void *request_ptr,
                                            size_t request_len,
                                            void *response_ptr,
                                            size_t response_len,
                                            size_t *response_lenout)
{
  (void)cxt;
  tz_app_cmd_handler((void*)request_ptr, (uint32_t)request_len, response_ptr, (uint32_t)response_len);
  *response_lenout = response_len;
  return Object_OK;
}

static IAppLegacyTest_DEFINE_INVOKE(CAppLegacyTest_invoke, CAppLegacyTest_, CAppLegacyTest *);

/**
 * Externally visible function: return an AppLegacyTest object
 */
int32_t CAppLegacyTest_open(Object* objOut)
{
  CAppLegacyTest *me = QSEE_ZALLOC_TYPE(CAppLegacyTest);
  if (me == NULL) {
    return Object_ERROR_MEM;
  }

  me->refs = 1;

  *objOut = (Object) { CAppLegacyTest_invoke, me };
  return Object_OK;
}
