
bool setConfig(char* param, char* value) {
  // sets the corresponding config variable for 'param' to new value
  // does not trigger saving to flash
  // does not distinguish between config and config2 as this is only split on flash and web-interface

  Serial.print("setConfig - '");
  Serial.print(param);
  Serial.print("' to '");
  Serial.print(value);
  Serial.println("'");

  if ( strcmp(param, "devName") == 0 ) {
    strlcpy(deviceName, value, 31);
    //    deviceName[30] = '\0';
  }
  else if ( strcmp(param, "httpUser") == 0 ) {
    strlcpy(http_user, value, 31);
  }
  else if ( strcmp(param, "httpPass") == 0 ) {
    strlcpy(http_pass, value, 31);
  }
  else if ( strcmp(param, "usedRelais") == 0 ) {
    usedRelaisCount = atoi(value);
  }
  else if ( strcmp(param, "usedButtons") == 0 ) {
    usedButtonsCount = atoi(value);
  }
  else if ( strcmp(param, "mqttHost") == 0 ) {
    strlcpy(mqtt_server, value, 41);
    //mqtt_server[40] = '\0';
  }
  else if ( strcmp(param, "mqttPort") == 0 ) {
    mqtt_port = atoi(value);
  }
  else if ( strcmp(param, "mqttUser") == 0 ) {
    strlcpy(mqtt_user, value, 31);
  }
  else if ( strcmp(param, "mqttPass") == 0 ) {
    strlcpy(mqtt_pass, value, 31);
  }
  else if ( strcmp(param, "willTop") == 0 ) {
    strlcpy(mqtt_willTopic, value, 51);
  }
  else if ( strcmp(param, "willQos") == 0 ) {
    mqtt_willQos = atoi(value);
  }
  else if ( strcmp(param, "willRet") == 0 ) {
    if (atoi(value) == 1) mqtt_willRetain = true;
    else mqtt_willRetain = false;
  }
  else if ( strcmp(param, "willMsg") == 0 ) {
    strlcpy(mqtt_willMsg, value, 31);
  }
  else if ( strcmp(param, "inTop") == 0 ) {
    strlcpy(mqtt_topic_in, value, 51);
  }
  else if ( strcmp(param, "outTop") == 0 ) {
    strlcpy(mqtt_topic_out, value, 51);
  }
  else if ( strcmp(param, "outTop_hold1") == 0 ) {
    strlcpy(mqtt_topic_out_hold_1, value, 51);
  }
  else if ( strcmp(param, "outTop_hold2") == 0 ) {
    strlcpy(mqtt_topic_out_hold_2, value, 51);
  }
  else if ( strcmp(param, "outTop_hold3") == 0 ) {
    strlcpy(mqtt_topic_out_hold_3, value, 51);
  }
  else if ( strcmp(param, "outPld_hold1") == 0 ) {
    Serial.print("set outPld_hold1");
    strlcpy(mqtt_payload_out_hold_1, value, 31);
  }
  else if ( strcmp(param, "outPld_hold2") == 0 ) {
    Serial.print("set outPld_hold2");
    strlcpy(mqtt_payload_out_hold_2, value, 31);
  }
  else if ( strcmp(param, "outPld_hold3") == 0 ) {
    Serial.print("set outPld_hold3");
    strlcpy(mqtt_payload_out_hold_3, value, 31);
  }
  else if ( strcmp(param, "domoIdx1") == 0 ) {
    domoticzIdx[0] = atoi(value);
  }
  else if ( strcmp(param, "domoIdx2") == 0 ) {
    domoticzIdx[1] = atoi(value);
  }
  else if ( strcmp(param, "domoIdx3") == 0 ) {
    domoticzIdx[2] = atoi(value);
  }
  else if ( strcmp(param, "domoOutTop") == 0 ) {
    strlcpy(domoticz_out_topic, value, 51);
  }
  else if ( strcmp(param, "impuls1") == 0 ) {
    relais_impulse[0] = atoi(value);
  }
  else if ( strcmp(param, "impuls2") == 0 ) {
    relais_impulse[1] = atoi(value);
  }
  else if ( strcmp(param, "impuls3") == 0 ) {
    relais_impulse[2] = atoi(value);
  }
}

void printConfig() {
  // prints current config vars to serial
  Serial.print("devName: ");
  Serial.println(deviceName);
  Serial.print("httpUser: ");
  Serial.println(http_user);
  Serial.print("httpPass: ");
  Serial.println(http_pass);
  Serial.print("mqttHost: ");
  Serial.println(mqtt_server);
  Serial.print("mqttPort: ");
  Serial.println(mqtt_port);
  Serial.print("mqttUser: ");
  Serial.println(mqtt_user);
  Serial.print("mqttPass: ");
  Serial.println(mqtt_pass);
  Serial.print("inTop: ");
  Serial.println(mqtt_topic_in);
  Serial.print("outTop: ");
  Serial.println(mqtt_topic_out);
  Serial.print("willTop: ");
  Serial.println(mqtt_willTopic);
  Serial.print("willQos: ");
  Serial.println(mqtt_willQos);
  Serial.print("willRet: ");
  Serial.println(mqtt_willRetain);
  Serial.print("willMsg: ");
  Serial.println(mqtt_willMsg);
  Serial.print("domoOutTop: ");
  Serial.println(domoticz_out_topic);

  Serial.print("usedRelais: ");
  Serial.println(usedRelaisCount);
  Serial.print("usedButtons: ");
  Serial.println(usedButtonsCount);
  Serial.print("outTop_hold1: ");
  Serial.println(mqtt_topic_out_hold_1);
  Serial.print("outTop_hold2: ");
  Serial.println(mqtt_topic_out_hold_2);
  Serial.print("outTop_hold3: ");
  Serial.println(mqtt_topic_out_hold_3);
  Serial.print("outPld_hold1: ");
  Serial.println(mqtt_payload_out_hold_1);
  Serial.print("outPld_hold2: ");
  Serial.println(mqtt_payload_out_hold_2);
  Serial.print("outPld_hold3: ");
  Serial.println(mqtt_payload_out_hold_3);
  Serial.print("domoIdx1: ");
  Serial.println(domoticzIdx[0]);
  Serial.print("domoIdx2: ");
  Serial.println(domoticzIdx[1]);
  Serial.print("domoIdx3: ");
  Serial.println(domoticzIdx[2]);
  Serial.print("impuls1: ");
  Serial.println(relais_impulse[0]);
  Serial.print("impuls2: ");
  Serial.println(relais_impulse[1]);
  Serial.print("impuls3: ");
  Serial.println(relais_impulse[2]);

  Serial.println();
}

bool loadConfig() { // loadConfig 1
  if (SPIFFS.exists("/config.json")) {
    File configFile = SPIFFS.open("/config.json", "r");
    if (!configFile) {
      Serial.println("ERR: Failed to open file /config.json");
      return false;
    }
    else {
      Serial.println("file /config.json opened");
      size_t size = configFile.size();

      Serial.print("file size: ");
      Serial.println(size);

//      Serial.println("file content:");
//
//      while (configFile.available()) {
//        //Lets read line by line from the file
//        String line = configFile.readStringUntil('\n');
//        Serial.println(line);
//      }
//      Serial.println();

      if (size > 900) {
        Serial.println("Config file size is too large");
        return false;
      }

      Serial.println("allocate buffer");
      // Allocate a buffer to store contents of the file.
      std::unique_ptr<char[]> buf(new char[size]);

      Serial.println("read file bytes to buffer");
      // We don't use String here because ArduinoJson library requires the input
      // buffer to be mutable. If you don't use ArduinoJson, you may as well
      // use configFile.readString instead.
      configFile.readBytes(buf.get(), size);

      Serial.println("create json buffer");

      StaticJsonBuffer<800> jsonBuffer;

      Serial.println("parse json data");

      JsonObject& json = jsonBuffer.parseObject(buf.get());

      Serial.println("do her kumm ma a no");

      if (!json.success()) {
        Serial.println("Failed to parse config file");
        return false;
      }

      Serial.println("und da ?");
      strlcpy(deviceName, json["devName"] | "", 31);
      strlcpy(http_user, json["httpUser"] | "", 31);
      strlcpy(http_pass, json["httpPass"] | "", 31);
      strlcpy(mqtt_server, json["mqttHost"] | "", 41);
      mqtt_port = atoi(json["mqttPort"] | "");
      strlcpy(mqtt_user, json["mqttUser"] | "", 31);
      strlcpy(mqtt_pass, json["mqttPass"] | "", 31);
      strlcpy(mqtt_topic_in, json["inTop"] | "", 51);
      strlcpy(mqtt_topic_out, json["outTop"] | "", 51);
      strlcpy(mqtt_willTopic, json["willTop"] | "", 51);
      mqtt_willQos = atoi(json["willQos"] | "0");
      if (atoi(json["willRet"] | "") == 1) mqtt_willRetain = true;
      else mqtt_willRetain = false;
      strlcpy(mqtt_willMsg, json["willMsg"] | "", 31);
      strlcpy(domoticz_out_topic, json["domoOutTop"] | "", 51);

      Serial.println("Loaded config values:");
      printConfig();
      return true;
    }
    configFile.close();
  }
  else {
    Serial.println("file /config.json file does not exist");
    return false;
  }


} // loadConfig 1

bool loadConfig2() {
  if (SPIFFS.exists("/config2.json")) {
    File configFile = SPIFFS.open("/config2.json", "r");
    if (!configFile) {
      Serial.println("ERR: Failed to open file /config2.json");
      return false;
    }
    else {
      Serial.println("file /config2.json opened");
      size_t size = configFile.size();
      Serial.print("file size: ");
      Serial.println(size);
      if (size > 800) {
        Serial.println("Config file size is too large");
        return false;
      }

      // Allocate a buffer to store contents of the file.



      std::unique_ptr<char[]> buf(new char[size]);



      // We don't use String here because ArduinoJson library requires the input
      // buffer to be mutable. If you don't use ArduinoJson, you may as well
      // use configFile.readString instead.
      configFile.readBytes(buf.get(), size);

      StaticJsonBuffer<810> jsonBuffer;
      JsonObject& json = jsonBuffer.parseObject(buf.get());

      if (!json.success()) {
        Serial.println("Failed to parse config file");
        return false;
      }

      usedRelaisCount = atoi(json["usedRelais"] | "");
      usedButtonsCount = atoi(json["usedButtons"] | "");
      strlcpy(mqtt_topic_out_hold_1, json["outTop_hold1"] | "", 51);
      strlcpy(mqtt_topic_out_hold_2, json["outTop_hold2"] | "", 51);
      strlcpy(mqtt_topic_out_hold_3, json["outTop_hold3"] | "", 51);
      strlcpy(mqtt_payload_out_hold_1, json["outPld_hold1"] | "", 31);
      strlcpy(mqtt_payload_out_hold_2, json["outPld_hold2"] | "", 31);
      strlcpy(mqtt_payload_out_hold_3, json["outPld_hold3"] | "", 31);
      domoticzIdx[0] = atoi(json["domoIdx1"] | "");
      domoticzIdx[1] = atoi(json["domoIdx2"] | "");
      domoticzIdx[2] = atoi(json["domoIdx3"] | "");
      relais_impulse[0] = atoi(json["impuls1"] | "");
      relais_impulse[1] = atoi(json["impuls2"] | "");
      relais_impulse[2] = atoi(json["impuls3"] | "");

      Serial.println("Loaded config values:");
      printConfig();
      return true;
    }
  }
  else {
    Serial.println("file /config2.json file does not exist");
    return false;
  }
}


bool saveConfig() { // safeConfig
  StaticJsonBuffer<810> jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();

  json["devName"] = deviceName;
  json["httpUser"] = http_user;
  json["httpPass"] = http_pass;
  json["mqttHost"] = mqtt_server;
  json["mqttPort"] = mqtt_port;
  json["mqttUser"] = mqtt_user;
  json["mqttPass"] = mqtt_pass;
  json["willTop"] = mqtt_willTopic;
  json["willQos"] = mqtt_willQos;
  json["willRet"] = mqtt_willRetain;
  json["willMsg"] = mqtt_willMsg;
  json["inTop"] = mqtt_topic_in;
  json["outTop"] = mqtt_topic_out;
  json["domoOutTop"] = domoticz_out_topic;

  File configFile = SPIFFS.open("/config.json", "w");
  if (!configFile) {
    Serial.println("Failed to open config file for writing");
    return false;
  }

  json.printTo(configFile);
  return true;
} // safeConfig


bool saveConfig2() { // safeConfig2
  StaticJsonBuffer<810> jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();

  json["usedRelais"] = usedRelaisCount;
  json["usedButtons"] = usedButtonsCount;
  json["outTop_hold1"] = mqtt_topic_out_hold_1;
  json["outTop_hold2"] = mqtt_topic_out_hold_2;
  json["outTop_hold3"] = mqtt_topic_out_hold_3;
  json["outPld_hold1"] = mqtt_payload_out_hold_1;
  json["outPld_hold2"] = mqtt_payload_out_hold_2;
  json["outPld_hold3"] = mqtt_payload_out_hold_3;
  json["domoIdx1"] = domoticzIdx[0];
  json["domoIdx2"] = domoticzIdx[1];
  json["domoIdx3"] = domoticzIdx[2];
  json["impuls1"] = relais_impulse[0];
  json["impuls2"] = relais_impulse[1];
  json["impuls3"] = relais_impulse[2];

  File configFile = SPIFFS.open("/config2.json", "w");
  if (!configFile) {
    Serial.println("Failed to open config2 file for writing");
    return false;
  }

  json.printTo(configFile);
  return true;
} // safeConfig2

void checkSaveConfigTriggered() {
  if (saveConfigToFlash) {
    saveConfigToFlash = false;
    saveConfig();
  }
  if (saveConfig2ToFlash) {
    saveConfig2ToFlash = false;
    saveConfig2();
  }
}
