#include "cvend.h"
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include "nfc.h"

void nfc_init(const char *path)
{
	uint8_t desfire_enable[] = { 0x00, CTYPE_DESFIRE, 0x01, FUNC_ENABLE };

	cvend_init(path);
	cvend_write(MTYPE_PROX_CARD_FUNCTION, desfire_enable, 4);
}

void *nfc_heartbeat(void *data)
{
	uint8_t heartbeat[2] = { 0x00, 0x00 };
	while (1) {
		cvend_write(MTYPE_STATUS, heartbeat, 2);
		sleep(10);
	}
	return NULL;
}

void *nfc_handle(void *data)
{
	pthread_t heartbeat_thread;
	pthread_create(&heartbeat_thread, NULL, nfc_heartbeat, NULL);
	nfc_cb callback = data;
	uint8_t desfire_select_application[] = { 0x5a, 0xF2, 0x10, 0xE0 };
	// uint8_t desfire_fid_list[] = { 0xf5, 0x00 };
	uint8_t desfire_get_version[] = { 0x60 };
	uint8_t desfire_read[] = { 0xbd, 0x00, 0x00, 0x00,
				   0x00, 0x00, 0x00, 0x00 };
	while (1) {
		cvend_packet *packet = cvend_read();

		if (packet->msg_type != MTYPE_DESFIRE_READ) {
			cvend_free(packet);
			continue;
		}
		cvend_free(packet);

		cvend_write(MTYPE_DESFIRE_COMMAND,
			    desfire_select_application, 4);
		cvend_free(cvend_read_type(MTYPE_DESFIRE_COMMAND_REPLY));

		cvend_write(MTYPE_DESFIRE_COMMAND, desfire_get_version,
			    1);
		cvend_packet *resp_version =
			cvend_read_type(MTYPE_DESFIRE_COMMAND_REPLY);

		if (resp_version->msg_len == 2 && resp_version->msg_data[1] == 0x6e) {
			cvend_free(resp_version);
			continue;
		}

		cvend_write(MTYPE_DESFIRE_COMMAND, desfire_read, 8);
		cvend_packet *resp_data =
			cvend_read_type(MTYPE_DESFIRE_COMMAND_REPLY);
		callback(resp_data->msg_data[0], resp_version->msg_data,
			 resp_version->msg_len, resp_data->msg_data,
			 resp_version->msg_len);
		cvend_free(resp_version);
		cvend_free(resp_data);
	}
	return NULL;
}
