// src/hardware/uart.cpp
#include "uart.h"
#include <cstring>

UartReader::UartReader(BufferedSerial &serial) : serial_port(serial) {
  memset(rx_buffer, 0, sizeof(rx_buffer));
  memset(message, 0, sizeof(message));
}

UartEvent UartReader::poll() {
  bool changed = false;
  bool triggered = false;

  // cita spravu z uartu
  if (serial_port.readable()) {
    memset(rx_buffer, 0, sizeof(rx_buffer));
    ssize_t num = serial_port.read(rx_buffer, sizeof(rx_buffer) - 1);
    if (num > 0) {
      strncpy(message, rx_buffer, sizeof(message) - 1);
      message_active = true;
      changed = true;
      triggered = true;
    }
  }

  // casovac na 1s zobrazenia spravy
  if (!timer_started) {
    msg_timer.start();
    timer_started = true;
  }

  // po jednu sekundu sa sprava zobrazi
  if (message_active && msg_timer.elapsed_time() > MESSAGE_DISPLAY_DURATION) {
    message_active = false;
    memset(message, 0, sizeof(message));
    msg_timer.reset();
    changed = true;
  }

  if (triggered)
    return UartEvent::Triggered;
  if (changed)
    return UartEvent::MessageUpdate;
  return UartEvent::NoChange;
}

const char* UartReader::get_message() const {
  return message_active ? message : nullptr;
}
