/*
 * Copyright (C) 2019 SAMSUNG S.LSI
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef ESE_U_BOOT_BUILD
#include <linux/types.h>
#include <linux/string.h>
#else
#include <stdlib.h>
#endif

#include <ese_log.h>
#include <ese_util.h>
#include <ese_api.h>
#include "ese_protocol.h"

#define LOG_TAG "ESE_API"
#define RELEASE_BUILD


#ifdef RELEASE_BUILD
#define API
#else
#define API __attribute__((visibility("default")))
#endif

API ESE_STATUS ese_open(void)
{
	ESE_STATUS status;

	status = eseProtocol_open();
	if (status != ESESTATUS_SUCCESS) {
		ESELOG_E("eseProtocol_open is failed : %04X", status);
	}

	return status;
}

API ESE_STATUS ese_close(void)
{	
	ESE_STATUS status;

	status = eseProtocol_close();
	if (status != ESESTATUS_SUCCESS) {
		ESELOG_E("eseProtocol_close is failed : %d", status);
	}

	return status;
}

API ESE_STATUS ese_reset(void)
{
	ESE_STATUS status;

	status = eseProtocol_reset();
	if (status != ESESTATUS_SUCCESS) {
		ESELOG_E("eseProtocol_reset is failed : %d", status);
		return status;
	}

	return status;
}

API ESE_STATUS ese_transceive(uint8_t *cmd, uint32_t cmd_len, uint8_t **rsp, uint32_t *rsp_len)
{
	ESE_STATUS status = ESESTATUS_SUCCESS;
	ese_data cmd_data;
	ese_data rsp_data;

	if ((cmd == NULL) || (cmd_len == 0) || (rsp == NULL) || (rsp_len == NULL)) {
		ESELOG_E("%s - Invalid paramter or no data", __FUNCTION__);
		return ESESTATUS_INVALID_PARAMETER;
	} else {
		memset(&cmd_data, 0x00, sizeof(ese_data));
		memset(&rsp_data, 0x00, sizeof(ese_data));

		cmd_data.len = cmd_len;
		cmd_data.p_data = cmd;

		status = eseProtocol_transceive(&cmd_data, &rsp_data);
		if (status != ESESTATUS_SUCCESS) {
			ESELOG_E("eseProtocol_transceive is Failed %d ", status);
			if(rsp_data.p_data)
				ESE_FREE(rsp_data.p_data);
			return status;
		}

		*rsp = rsp_data.p_data;
		*rsp_len = rsp_data.len;
	}

	return status;
}
