#include "webserver.h"
 
using namespace websockets;
WebsocketsServer server;
AsyncWebServer webserver(80);
WebsocketsClient client;

#define PARAMCOUNT 4

// handle http messages
void handle_message(WebsocketsMessage msg) {
  log_v("ws data received: %s", msg.data());
  bool parsing = true;
  int commaIndex=0, previndex=0;
  std::vector<int> params;

  while(parsing)
  {
    commaIndex = msg.data().indexOf(',', previndex);
    log_v("commaindex:%i, previndex:%i", commaIndex, previndex);

    if(commaIndex == -1)
    {
      if(previndex > 0)
      {
        int value = msg.data().substring(previndex + 1).toInt();
        log_v("got value(%d): %i", params.size()+1, value);
        params.push_back(value);
      }
      log_v("end of message (param count=%u)", params.size());
      parsing = false;
    }
    else
    {
      int value = msg.data().substring(previndex, commaIndex).toInt();
      log_v("got value(%d): %i", params.size()+1, value);
      params.push_back(value);
      delay(5);
      previndex = commaIndex+1;
    }
  }

  if(params.size() < PARAMCOUNT)
  {
    log_e("message inclomplete size=%u", params.size());
    return;
  }
  
  drivemotor(0, params[0]);
  drivemotor(1, params[1]);
  drivemotor(2, params[2]);
  bucketTilt(params[3]);
}

void setup_webserver()
{
  // HTTP handler assignment
  webserver.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", web_smars_html_gz, web_smars_html_gz_len);
    response->addHeader("Content-Encoding", "gzip");
    request->send(response);
  });

  // start server
  webserver.begin();
  server.listen(82);
  log_i("Is server live? %s",server.available() ? "true" : "false");
 
  client = server.accept();
  client.onMessage(handle_message);
}
 

uint32_t webservertimer = 0;

void loop_webserver()
{
  if(millis() - webservertimer > WEBSERVER_LOOP)
  {
    if (client.available()) 
    {
      client.poll();
    }
    else
    {
      if(!server.available())
      {
        log_e("server not available");
      }
      log_w("client not available");
    }
    webservertimer = millis();
  }

}