/// © MiroZ 2024

#include <stdlib.h>
#include <esp_err.h>
#include <string.h>

#include "ReaderWriter.h"
#include <Arduino.h>

ReaderWriter::ReaderWriter(uint32_t buffer_len) : Parser("|"), m_buffer_len(buffer_len)
{
	assert(m_buffer = (char*)malloc(buffer_len));
	reset();
}

ReaderWriter::~ReaderWriter()
{
	if(m_buffer)
		free(m_buffer);
}

void ReaderWriter::reset()
{
	m_buffer[0] = 0;
	m_available = m_buffer_len;
	m_write_ptr = 0;
}

/// @brief Appends str to the internal buffer
/// @param str 
/// @return number of bytes left in the buffer or 0 if str can't fit in the space left.
uint32_t ReaderWriter::append(const char * str)
{
	uint32_t len = strlen(str);

	if(len + 1 > m_available)
		return 0;

	strcpy(&m_buffer[m_write_ptr], str);
	m_write_ptr += len;
	m_available -= len;

	return m_available;
}

uint32_t ReaderWriter::appendf(const char * format, ... )
{
	va_list arg;
	char buf[256];
	va_start(arg, format);
	vsprintf(buf, format, arg);
	va_end(arg);
	return append(buf);
}

uint32_t ReaderWriter::append(int32_t value, uint32_t base)
{
	String s;
	char buf[32];
	itoa(value, buf, 10);
	return append(buf);
}

uint32_t ReaderWriter::append(char c)
{
	if(m_available < 2)
		return 0;

	m_buffer[m_write_ptr++] = c;
	m_buffer[m_write_ptr] = 0;
	m_available--;

	return m_available;
}

char * ReaderWriter::getBuffer()
{
	return m_buffer;
}

uint32_t ReaderWriter::getLen()
{
	return m_write_ptr;
}

void ReaderWriter::copyString(const char *str)
{
	reset();
	strcpy(m_buffer, str);
}
