#include "otaupdate.h"
#include "LittleFS.h"
#include <HTTPClient.h>
#include <Update.h>
#include "githubCert.h"
#include <ArduinoJson.h>


String binFile = "manifest.json";
String rootUrl = "https://raw.githubusercontent.com/ataindustries/atacontrolboardV1/main/";
String github_token = "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"; 

const float FirmwareVer = 1.0;

JsonDocument doc;

int otaupdate_check(void)
{/*
  String payload;
  int httpCode;
  WiFiClientSecure * client = new WiFiClientSecure;
  HTTPClient https;

  String manifest_url = rootUrl + binFile + "?token=" + github_token;
  https.begin(manifest_url);
  httpCode = https.GET();

  if (httpCode == HTTP_CODE_OK) // if version received
  {
    String payload = https.getString();
    JsonDocument doc;
    deserializeJson(doc, payload);

    float firmver = doc["firmver"].as<float>();
    const char* firmfile = doc["firmfile"];
    const char* fsfile = doc["fsfile"];

    Serial.printf("From manifest: %.1f, %s, $s\n\r", firmver, firmfile, fsfile);

    if(firmver > FirmwareVer){
      Serial.println("New firmware available!");
      return 1;
    }else{
      Serial.println("firmware is upto date!");
      return 0;
    }
  }
  */
  return 0;
}

void otaupdate_perform(void)
{

  // setup events
  ota_events();


  // Pause unnecessary tasks

  //check for update
}

void ota_events(void)
{
  /*
  fota->setUpdateEndCb( [](int partition) 
  {
    //Serial.printf("Update could not finish with %s partition\n", partition==U_SPIFFS ? "spiffs" : "firmware" );
  });

  fota->setProgressCb( [](size_t progress, size_t size) 
  {
    //if( progress == size || progress == 0 ) Serial.println();
    //Serial.print(".");
  });

  fota->setUpdateCheckFailCb( [](int partition, int error_code)
  {
    //Serial.printf("Update could validate %s partition (error %d)\n", partition==U_SPIFFS ? "spiffs" : "firmware", error_code );
    // error codes:
    //  -1 : partition not found
    //  -2 : validation (signature check) failed
  });

  fota->setUpdateFinishedCb( [](int partition, bool restart_after) 
  {
    //Serial.printf("Update could not begin with %s partition\n", partition==U_SPIFFS ? "spiffs" : "firmware" );

    if( restart_after ) {
        ESP.restart();
    }
  });
  */
}

