#include "FSUpdater.h"
#include <ESP8266HTTPClient.h>
#include <FS.h>


void FSUpdater::freeMemory() {
  /*
  if (bom != NULL) free(bom);
  bom = NULL;
  */
  if (bomBuffer != NULL) free(bomBuffer);
  bomBuffer = NULL;
  bomCounter = 0;
  errorMessage = String();
}

void FSUpdater::manageFsOtaBom(String payload) {
  freeMemory();
  //bom = malloc(sizeof(BomEntry) * MAX_FILES);
  bomBuffer = (char *) malloc(payload.length()+1);
  payload.toCharArray(bomBuffer, payload.length()+1);
  memset(bom, sizeof(BomEntry) * MAX_FILES_IN_BOM, 0);

  char *parsePtr = bomBuffer; // to start
  while (*parsePtr != 0) {
    bom[bomCounter].executionMark = *parsePtr;
    if (*parsePtr != ':') { errorMessage = String("Wrong seperation character ") + String(*parsePtr) + " at line " + String(bomCounter+1); return; }
    ++parsePtr;

    bom[bomCounter].localFilename = parsePtr;
    while (*parsePtr != ':' && *parsePtr != 0) ++parsePtr;
    *parsePtr++ = 0; // End of string for localFilename

    char *size_string = parsePtr;
    while (*parsePtr != ':' && *parsePtr != 0) ++parsePtr;
    *parsePtr++ = 0; // End of string for localFilename
    bom[bomCounter].filesize = atol(size_string);

    bom[bomCounter].md5 = parsePtr;
    while (*parsePtr != ':' && *parsePtr != 0) ++parsePtr;
    *parsePtr++ = 0; // End of string for localFilename

    bom[bomCounter].remoteFilename = parsePtr;
    while (*parsePtr != ':' && *parsePtr != 0 && *parsePtr != '\n' && *parsePtr != '\r') ++parsePtr;
    *parsePtr++ = 0; // End of string for localFilename

    // skip trailing characters if these are seperators or end of line
    while (*parsePtr == ':' || *parsePtr == '\n' || *parsePtr == '\r' || *parsePtr == ' ') ++parsePtr;
    ++bomCounter;
    if (bomCounter != MAX_FILES_IN_BOM) { errorMessage = "Too many files in BOM, max=" + String(MAX_FILES_IN_BOM); return; }
  }
}

void FSUpdater::checkForUpdates() {
  HTTPClient http;

  //http.begin("https://192.168.1.12/test.html", "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38"); //HTTPS
  http.begin(baseUrl + "/" + swVersion + "/bom"); //HTTP
  Serial.printf("[HTTP] GET %s/%s/bom", baseUrl.c_str(), swVersion.c_str());
  // start connection and send HTTP header
  int httpCode = http.GET();

  // httpCode will be negative on error
  if (httpCode > 0) {
    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      manageFsOtaBom(payload);
    }
  } else {
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }

  http.end();
}
