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

// Constructor
SerialProcess::SerialProcess(int addr) 
    : address(addr), ndx(0), rc(0), newData(false), rcCheck(false) {
    Serial.begin(115200);
}

// Processes Serial Input
void SerialProcess::SerialInput() {
    while (Serial.available() > 0) {
        rc = static_cast<char>(Serial.read());

        if (rc == beginMarker) {
            rcCheck = true;  // Start reading after the begin marker
            ndx = 0;         // Reset index for new message
        }

        if (rcCheck) {
            // Store the character if within bounds
            if (ndx < numChars - 1) {
                receivedChars[ndx++] = rc;
            }

            // Check for end marker
            if (rc == endMarker) {
                receivedChars[ndx] = '\0';  // Null-terminate the string
                newData = true;             // Mark new data as available
                rcCheck = false;            // Stop reading until the next begin marker
            }
        }
    }
}

// Check if new data is available
bool SerialProcess::isNewDataAvailable() {
    return newData;
}

// Get the received data
char* SerialProcess::getReceivedData() {
    if (newData) {
        newData = false;  // Reset the flag after accessing the data
        return receivedChars;
    }
    return nullptr;  // No new data
}

// Process the received message
void SerialProcess::getPayload(char *payload) {
    if (newData) {
        uint8_t source;
        uint8_t destination;  
        char data[255];  // Allocate a buffer for the data  
        int parsed = sscanf(receivedChars, "#%hhu:%hhu:%63s;", &source, &destination, data);
        if (parsed == 3 && destination == address) {  // Ensure all fields are parsed correctly
            strcpy(payload, data);  // Copy data to the provided buffer
            newData = false;              // Mark the data as processed
        } else if (address != source) {
            Serial.print(receivedChars);  // Forward the message
        }
    }
}

// Send a message in the correct format
void SerialProcess::sendMessage(int receiver, const char* payload) {
    Serial.printf("#%u:%u:%s;", address, receiver, payload);
}


void SerialProcess::changeAddress(int addr) {
    address = addr;  // Update the device address
}