#include "DUREX.h"
#include "Hal.h"

DUREX_numBytes_t            numBytes = 0;
DUREX_data_t                data = "";
DUREX_numPackets_t          numPackets = 0;
DUREX_messageAvailable_t    messageAvailable = 0;
uint8_t                     lastMessageAck = 1;

void main() {
    Hal_init();
    DUREX_start();
    Hal_idleLoop();
}

/* -------- SCHEMA CALLBACKS -------- */

void processMessage()
{
	if(!strcmp(data,"Hello"))
	{
		memcpy(data,"Hello",6);
		numBytes = 6;
		numPackets = 1;
	}
}

void DUREX_connectHandler(void)
{
	Hal_connected();
}

void DUREX_disconnectHandler(void)
{
	Hal_disconnected();
}

void DUREX_numBytes_fetch(DUREX_numBytes_t* const output)
{
    *output = numBytes;
}

void DUREX_numBytes_store(DUREX_numBytes_t* const input)
{
	numBytes = *input;
}

void DUREX_data_fetch(DUREX_data_t output)
{
	memcpy(output,data,numBytes);
}

void DUREX_data_store(DUREX_data_t input)
{
	memcpy(data,input,numBytes);
}

void DUREX_numPackets_fetch(DUREX_numPackets_t* const output)
{
	*output = numPackets;
}

void DUREX_numPackets_store(DUREX_numPackets_t* const input)
{
    numPackets = *input;
}

void DUREX_messageAvailable_fetch(DUREX_messageAvailable_t* const output)
{
    *output = messageAvailable;
}

void DUREX_messageAvailable_store(DUREX_messageAvailable_t* const input)
{
	messageAvailable = *input;
	if(messageAvailable == DUREX_TRUE)
	{
		led1_on();
		lastMessageAck = 0;
		messageAvailable = DUREX_FALSE;
		DUREX_messageAvailable_indicate();
		processMessage();
		messageAvailable = DUREX_TRUE;
		DUREX_messageAvailable_indicate();
	}
	else if(messageAvailable == DUREX_FALSE)
	{
		led1_off();
		lastMessageAck = 1;
	}
}

