#include "Dtypes.h"
#include "MessageCodes.h"
#include "Logger.h"
#include "SwimTrackerConfig.h"

#include <ArduinoWebsockets.h>
#include <ArduinoJson.h>


class LoggingAPI
{
  public:
    void onClientConnect(websockets::WebsocketsClient &client, int /*clientId*/) {}

    bool handleMessage(websockets::WebsocketsClient &client, MessageCode code, const char *payload, size_t size) {
      switch(code) {
        case MessageCode::LOG_STREAMING_START:
          running_ = true;
          if(firstCall_) {
            const Logger * logger = Logger::getInstance();
            lastEnd_ = logger->begin();
            firstCall_ = false;
          }
          return true;
        case MessageCode::LOG_STREAMING_STOP:
          running_ = false;
          return true;
        default:
          return false;
      }
    }

    template <typename TServer>
    void iteration(TServer &server)
    {
      if(running_)
      {
        const Logger * logger = Logger::getInstance();

        const auto endIt = logger->end();
        StaticJsonDocument<1024> data;
        for(auto it = lastEnd_; it != endIt; ++it) {
            data["time"] = it.time_millis();
            data["msg"] = it.message();
            server.template sendToAll<1024>(MessageCode::LOG_UPDATE, data);
        }
        lastEnd_ = endIt;
      }
    }

  private:
    bool running_ = false;
    Logger::iterator lastEnd_ = Logger::iterator(nullptr);
    bool firstCall_ = true;
};

