#include "commandreader.h"
using namespace Xybrid::NodeLib;
using namespace Xybrid::Data;

#include "data/porttypes.h"


CommandReader::CommandReader(CommandPort* p) {
    p->pull();
    data = p->data;
    dataSize = p->dataSize;
}

CommandReader::operator bool() const { return dataSize >= cur+5; }
CommandReader& CommandReader::operator++() {
    if (cur == static_cast<size_t>(-1)) cur = 0;
    else if (dataSize >= cur+5) cur += 5 + data[cur+4]*2;
    return *this;
}

ParamReader::ParamReader(const CommandReader& cr) : cr(cr) {
    if (cr) {
        pmax = cr.data[cr.cur+4];
    }
}

ParamReader::operator bool() const { return pn >= 0 && pn < pmax; }
ParamReader &ParamReader::operator++() {
    ++pn;
    return *this;
}

int16_t ParamReader::next(bool acceptsTweens, uint8_t num) const {
    auto n = static_cast<uint8_t>(pn);
    while (++n < pmax) {
        auto p = cr.param(n);
        if (p != ',' && (acceptsTweens && p != 't')) break;
        if (p == ',' && --num == 0) return cr.val(n);
    }
    return -1;
}

int16_t ParamReader::tween() const {
    auto n = static_cast<uint8_t>(pn);
    while (++n < pmax) {
        auto p = cr.param(n);
        if (p == 't') return cr.val(n);
        if (p == ',') continue;
        break;
    }
    return -1;
}


