#include "SecureObject.h"
#include "TZ_Vendor_tl.h"
#include "tl_tui_bc_error_msg.h"
#include "TZ_Vendor_debug_tl.h"
#include "TZ_Vendor_Tui_common_tl.h"

static uint8_t gOutputSoData[TRANSACTION_SO_BUFFER_SIZE];
static uint32_t gOutputSoDataLength = sizeof(gOutputSoData);

uint32_t compareSoSource(uint8_t *so, uint32_t so_len, uint8_t *compare_source, uint32_t compare_len) {
	uint8_t so_source[128];
	uint32_t so_source_len = sizeof(so_source);

	memset(so_source, 0, sizeof(so_source));

	uint32_t ret_val = TZ_get_so_source(so, so_len, so_source, &so_source_len);
	if (ret_val != TUI_SUCCESS) {
		TTY_LOG("%s is_so_source_compare : Error identifying the secure obj source, ret = 0x%X", LOG_TAG, ret_val);
		return false;
	}

	DBG_LOG("%s is_so_source_compare : so_source %s", LOG_TAG, so_source);
	DBG_DUMP(so_source, so_source_len);
	DBG_LOG("%s is_so_source_compare : compare_source %s", LOG_TAG, compare_source);
	DBG_DUMP(compare_source, compare_len);

	if (so_source_len < compare_len) {
		TTY_LOG("so_source_len : %d < compare_len %d - %s", so_source_len, compare_len, so_source);
		return ERROR_BC_TUI;
	}

	if (memcmp(so_source, compare_source, compare_len)) {
		TTY_LOG("is_so_source_compare : Cannot verify the source of the secure object - %s", so_source);
		return SPAY_TPP_TUI_ERROR_REWRAP_PIN_SO;
	}

	return true;
}

void setOutputSoData(uint8_t *soData, uint32_t soLen) {
	memset(gOutputSoData, 0, gOutputSoDataLength);
	memcpy(gOutputSoData, soData, soLen);
	gOutputSoDataLength = soLen;
}

uint8_t* getOutputSoData(uint32_t* soDataLen) {
	*soDataLen = gOutputSoDataLength;
	return gOutputSoData;
}