#include <cstdint>
#include "ProtocolUnpacker.h"

using namespace Whill;

void Unpacker::feed(const char* const data, const uint8_t size)
{
    for (uint8_t i = 0; i < size; ++i) feed(data[i]);
}

void Unpacker::feed(char data)
{

    if (state != State::Checksum) sum ^= data;

    switch(state)
    {
        case State::Start:
        {
            reset();
            if (data == PROTOCOL_SIGN) state = State::Size;
            sum ^= data; // because sum was reset above
            break;
        }
        case State::Size:
        {
            r_buffer.size = data - 1; // exclude checksum
            state = State::Data;
            break;
        }
        case State::Data:
        {
            r_buffer.write(&data, 1);
            if (++count >= r_buffer.size) state = State::Checksum;
            break;
        }
        case State::Checksum:
        {
            if (sum == data) _readBuffer.push_back(r_buffer);
            reset();
            break;
        }
        default:
        {
            reset();
            break;
        }
    }
}

void Unpacker::reset()
{
    r_buffer.clear();
    sum = count = 0;
    state = State::Start;
}
