#ifndef DK_APDU_H
#define DK_APDU_H

#include <sec_apdu.h>

#include "dk_common.h"
#include "dk_constants.h"
#include "dk_utils.h"

// TZ OS can't allocat this much memory by default.
// Divide it by 4.
#define MAX_RESPONSE_SIZE    4096U // 2^16

/**
 * Extract status bytes from rpdu.
 * 
 * @param rpdu RPDU from which to extract SW.
 */
uint16_t get_sw(secEse_7816_rpdu_t *rpdu);

/**
 * Clear rpdu for reuse.
 * 
 * @param rpdu rpdu to be cleared.
 */
void rpdu_clear(secEse_7816_rpdu_t* rpdu);

/**
 * Convert a byte array to a cpdu.
 * 
 * @param buf byte array containing a cpdu.
 * @param buflen length of buf.
 * @param cpdu cpdu to which data will be written to
 * 
 * @return DK_SUCCESS on success; DK_ERROR_GENERIC on error.
 */
DK_Result barray_to_cpdu(byte* buf, size_t buflen, secEse_7816_cpdu_t* cpdu);

/**
 * Convert a rpdu to byte array.
 * 
 * @param dst byte array to which rpdu will be written to.
 * @param dstlen length of dst.
 * @param rpdu rpdu to be converted to byte array.
 * 
 * @return DK_SUCCESS on success; DK_ERROR_GENERIC on error.
 */
DK_Result rpdu_to_barray(byte* dst, size_t* dstlen, secEse_7816_rpdu_t* rpdu);

/**
 * Convert a byte array to a cpdu.
 * 
 * @param src byte array containing a rpdu.
 * @param size length of buf.
 * @param dest rpdu to which data will be written to
 * 
 * @return DK_SUCCESS on success; DK_ERROR_GENERIC on error.
 */
DK_Result barray_to_rpdu(byte* src, size_t size, secEse_7816_rpdu_t* dest);

/**
 * Clear buf.
 * 
 * @param buf buffer to be cleared.
 * @param buflen length of buf.
 */
void barray_clear(byte* buf, size_t buflen);

/**
 * Dump rpdu.
 * 
 * @param rpdu rpdu to be dumped
 */
void rpdu_dump(secEse_7816_rpdu_t* rpdu);

/**
 * Dump cpdu.
 * 
 * @param cpdu cpdu to be dumped
 */
void cpdu_dump(secEse_7816_cpdu_t* cpdu);

#endif