/*
 * Copyright (c) 2019, 2023 Qualcomm Technologies, Inc.
 * All Rights Reserved.
 * Confidential and Proprietary - Qualcomm Technologies, Inc.
 */

#include <stdint.h>
#include <stdio.h>

#include "example_listener.h"
#include "listener.h"
#include "listener_init.h"
#include "example_app.h"
#include "example_app_methods.h"
#include "run_listener.h"
#include "QSEEComAPI.h"

int run_listener(struct QSEECom_handle *app_handle)
{
  int error = LISTENER_FAILURE;
  int cleanup_error = LISTENER_FAILURE;

  struct example_app_req req = {0};
  struct example_app_rsp rsp = {0};

  struct listener_sendcmd_req listener_req = {0};
  struct listener_sendcmd_rsp listener_rsp = {0};

  struct listener_sendcmd_rsp *listener_result;

  error = setup_listener();
  if (error) {
    printf("Failed to setup listener.\n");
    return LISTENER_FAILURE;
  }

  listener_req_init(&listener_req, LISTENER_ID);

  example_app_req_listener_init(&req, &listener_req);
  example_app_rsp_listener_init(&rsp, &listener_rsp);

  error = QSEECom_send_cmd(app_handle, &req, sizeof(req), &rsp, sizeof(rsp));

  if (error != QSEECOM_SUCCESS) {
    goto out;
  }

  listener_result = example_app_rsp_get_rsp_struct(&rsp);
  if (!listener_result) {
    error = LISTENER_FAILURE;
    goto out;
  }

  if (listener_result->status == LISTENER_FAILURE) {
    error = LISTENER_FAILURE;
  }

out:
  cleanup_error = cleanup_listener();
  return (cleanup_error || error) ? LISTENER_FAILURE : LISTENER_SUCCESS;
}
