#include <FS.h>
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

//needed for library
#include <ESP8266WebServer.h>
#include <DNSServer.h>

#define DEBUG 0 //0=off 1=on

// Variables
const char* set_mqtt_user="quyhgw";
const char* set_mqtt_devid="1870";

// Default configuration values
char mqtt_user[9]; //le va lua din FS
char mqtt_devid[5]; //le va lua din FS

// Function Prototypes
bool readConfigFile();
bool writeConfigFile();

// Setup function
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  #if DEBUG
  Serial.println("\n Starting");
  #endif 

  // Mount the filesystem
  bool result = SPIFFS.begin();
  //Serial.println("SPIFFS opened: " + result);

  if (readConfigFile()) {
    #if DEBUG
    Serial.print("User:");
    Serial.println(mqtt_user);
    Serial.print("devid:");
    Serial.println(mqtt_devid);
    #endif
  }
  //WiFi.printDiag(Serial); //Remove this line if you do not want to see WiFi password printed

}

// Loop function

void loop() {
  // is configuration portal requested?
    writeConfigFile();
    delay(9999999);
}

bool readConfigFile() {
  // this opens the config file in read-mode
  File f = SPIFFS.open("/config.json", "r");
  
  if (!f) {
    #if DEBUG
    Serial.println("Configuration file not found");
    #endif
    return false;
  } else {
    // we could open the file
    size_t size = f.size();
    // Allocate a buffer to store contents of the file.
    std::unique_ptr<char[]> buf(new char[size]);

    // Read and store file contents in buf
    f.readBytes(buf.get(), size);
    // Closing file
    f.close();
    // Using dynamic JSON buffer which is not the recommended memory model, but anyway
    // See https://github.com/bblanchon/ArduinoJson/wiki/Memory%20model
    DynamicJsonBuffer jsonBuffer;
    // Parse JSON string
    JsonObject& json = jsonBuffer.parseObject(buf.get());
    // Test if parsing succeeds.
    if (!json.success()) {
      #if DEBUG
      Serial.println("JSON parseObject() failed");
      #endif
      return false;
    }
    #if DEBUG
    json.printTo(Serial);
    #endif
    strcpy(mqtt_user, json["mqtt_user"]);
    strcpy(mqtt_devid, json["mqtt_devid"]);
  }
  return true;
}

bool writeConfigFile() {
  #if DEBUG
  Serial.println("Saving config file");
  #endif
  DynamicJsonBuffer jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();

  // JSONify local configuration parameters
  json["mqtt_user"] = set_mqtt_user;
  json["mqtt_devid"] = set_mqtt_devid;

  // Open file for writing
  File f = SPIFFS.open("/config.json", "w");
  if (!f) {
    Serial.println("Instalation failed! Write error!");
    while (true){
      digitalWrite(LED_BUILTIN, HIGH);   // ledul face blink semn ca sunt probleme
      delay(400);                       
      digitalWrite(LED_BUILTIN, LOW);   
      delay(400);                       
    }
    return false;
  }

  json.prettyPrintTo(Serial);
  // Write data to file and close it
  json.printTo(f);
  f.close();

  Serial.println("\nDevice updated!");
  digitalWrite(LED_BUILTIN, LOW); // ledul ramane aprins semn ca s-au scris credentialele
  return true;
}

