#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>

// Constants
const int TRIGGER_PIN = 0; // D3 on NodeMCU and WeMos.

// Variables
const char* set_mqtt_user="exwrgq";
const char* set_mqtt_devid="2638";

// 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() {
  // Put your setup code here, to run once
  Serial.begin(115200);
  Serial.println("\n Starting");

  // Initialize trigger pins
  pinMode(TRIGGER_PIN, INPUT_PULLUP);

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

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

}

// Loop function

void loop() {
  // is configuration portal requested?
  if (digitalRead(TRIGGER_PIN) == LOW) {
     Serial.println("Configuration portal requested");
    writeConfigFile();
     Serial.println("writeconfigfile...done");
  }
}

bool readConfigFile() {
  // this opens the config file in read-mode
  File f = SPIFFS.open("/config.json", "r");
  
  if (!f) {
    Serial.println("Configuration file not found");
    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()) {
      Serial.println("JSON parseObject() failed");
      return false;
    }
    json.printTo(Serial);
    strcpy(mqtt_user, json["mqtt_user"]);
    strcpy(mqtt_devid, json["mqtt_devid"]);
  }
  return true;
}

bool writeConfigFile() {
  Serial.println("Saving config file");
  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("Failed to open config file for writing");
    return false;
  }

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

  Serial.println("\nConfig file was successfully saved");
  return true;
}