#include "meshtalos.h"
#include "lib/mongoose.h"
#include <string.h>

uint8_t image_buf[152 * 296] = {0};
bool flag_refresh = true;

static void ev_handler(struct mg_connection *c, int ev, void *ev_data) {

  struct Storage *storage = (struct Storage *)(ev_data);

  if (ev == MG_EV_HTTP_MSG) { // New HTTP request received
    struct mg_http_message *hm =
        (struct mg_http_message *)ev_data;             // Parsed HTTP request
    if (mg_match(hm->uri, mg_str("/api/tag"), NULL)) { // REST API call?
      if (hm->body.len == sizeof(image_buf)) {
        memcpy(image_buf, hm->body.buf, sizeof(image_buf));
        mg_http_reply(c, 200, "", "fin");
        flag_refresh = true;
        return;
      }
      mg_http_reply(c, 400, "", "bad");

    } else {
      mg_http_reply(c, 404, "", "bad req");
    }
  }
}

struct Meshtalos *mtsh_init() {
  struct Meshtalos *mtsh = calloc(1, sizeof(struct Meshtalos));
  if (mtsh == NULL) {
    return NULL;
  }

  // if ((mtsh->storage = storage_init()) == NULL) {
  //   goto lfs_err;
  // }
  mg_mgr_init(&mtsh->mg);

  return mtsh;
  // lfs_err:
  //   if (mtsh != NULL) {
  //     free(mtsh);
  //   }
  //   return NULL;
}

void mtsh_listen(struct Meshtalos *mtsh, const char *http_endpoint) {
  mg_http_listen(&mtsh->mg, http_endpoint, ev_handler, &mtsh->storage);
  mtsh_tcp_sender(&mtsh->mg);
  for (;;) {
    mg_mgr_poll(&mtsh->mg, 1000);
  }
}
