#include "dsr.h"

/*Builds a struct for the header with the values specified, if one value is not valid
 this one is replaced with a standard valid one, which is not necessarily working as 
 willed by the user.*/
_dsr_header _dsrMakeHeader(uint8_t src, uint8_t dst, uint8_t req_id, uint8_t type, uint8_t jump, uint8_t ttl, uint8_t p_len) {
_dsr_header h;

	/*Source*/
	//if (!NODE_IN_LIMS(src))	h.src = NODE_MIN;
	//else			h.src = src;
	h.src = src;

	/*Destination*/
	//if (!NODE_IN_LIMS(dst))	h.dst = NODE_MIN;
	//else			h.dst = dst;
	h.dst = dst;

	/*Request id*/
	h.req_id = req_id;

	/*Type*/
	if (type != ROUTE_REPLY && type != ROUTE_REQUEST)	h.type = ROUTE_REQUEST;
	else							h.type = type;

	/*Jump pointer*/
	h.jump = jump;

	/*Time to live*/
	h.ttl = ttl;

	/*Payload length*/
	h.payload_len = p_len;


return h;
}


/*Builds a payload with the values specified, if the payload tries to be NULL
  so it will be, no restrictions for that. Memory management is the user's
  responsability. */
_dsr_payload _dsrMakePayload(uint8_t *data) {
_dsr_payload p;

	p.data = data;

return p;
}


/*Builds a packet with the specified structures of a header and a payload*/
_dsr_packet _dsrMakePacket(_dsr_header h, _dsr_payload p) {
_dsr_packet packet;

	packet.h = h;
	packet.p = p;

return packet;
}


/*Builds a packet (essentially an array) of bytes ready to be sent, here we reserve memory
  which can be freed by the user or using */
uint8_t *_dsrMakeFrame(_dsr_packet p) {
uint8_t *frame = NULL;
uint8_t i=0;

	frame = malloc(HEADER_LEN + p.h.payload_len);

	frame[0] = p.h.src;
	frame[1] = p.h.dst;
	frame[2] = p.h.req_id;
	frame[3] = p.h.type;
	frame[4] = p.h.jump;
	frame[5] = p.h.ttl;
	frame[6] = p.h.payload_len;

	for (i=0;i<p.h.payload_len;i++)
		frame[HEADER_LEN + i] = p.p.data[i];

return frame;
}

/*Frees the frame previously reserved*/
int _dsrFreeFrame(uint8_t *frame) {

	if (!frame) return -1;

	free(frame);

return 0;
}




