#pragma once

extern uint16_t relayDurations[16];

void loadRelayTimings();
void saveRelayTimings();

// - - - - - - - - - - - - - - - - - - - - - - - - - - -



// Sets Incoming Relay Durations to RAM and then call funtion to save them to file.
void updateRelayTimings(JsonDocument doc) {
    // Iterate through the relays in the JSON payload
    for (uint8_t i = 0; i < 16; i++) {
        String key = String("b") + (i + 1); // Generate "b1", "b2", ...
        if (doc.containsKey(key)) {
            relayDurations[i] = doc[key].as<uint16_t>();
            Serial.printf("Relay %d duration set to %d ms\n", i + 1, relayDurations[i]);
        } else {
            Serial.printf("Relay %d not found in JSON payload. Keeping previous duration: %d ms\n", i + 1, relayDurations[i]);
        }
    }
		saveRelayTimings();
}

// Save file "fileName" with data: "data"
void savefile(const char* fileName, const char* data) {
    File file = SPIFFS.open(fileName, "w");
    if (!file) {
        Serial.println("Failed to open file!");
        return;
    }
    file.print(data);
    file.close();
    Serial.printf("File %s saved successfully.\n", fileName);
}

// Saves Relay Durations from RAM, into a file
void saveRelayTimings() {
    StaticJsonDocument<512> doc; // Adjust size if needed

    // Populate the JSON object with relay durations
    for (uint8_t i = 0; i < 16; i++) {
        String key = String("b") + (i + 1);
        doc[key] = relayDurations[i];
    }

		char buffer[512];
		size_t len = serializeJson(doc, buffer, sizeof(buffer));
		if (len == 0) {
			Serial.println("Failed to serialize JSON.");
			return;
		}

		const char * fileName = "/settings/relayTimings.json";
		savefile(fileName, buffer);

    // // Open the file for writing
    // File file = SPIFFS.open("/settings/relayTimings.json", "w");
    // if (!file) {
    //     Serial.println("Failed to open file for writing");
    //     return;
    // }
		//
    // // Serialize JSON to the file
    // if (serializeJson(doc, file) == 0) {
    //     Serial.println("Failed to write JSON to file");
    // } else {
    //     Serial.println("Relay timings saved successfully");
    // }
		//
    // file.close();
}

// Loads Relay Durations from file into RAM (called during boot)
void loadRelayTimings() {
    // Open the file for reading
    File file = SPIFFS.open("/settings/relayTimings.json", "r");
    if (!file) {
        Serial.println("Settings file not found. Using default relay timings.");
        return;
    }

    // Parse the JSON file
    StaticJsonDocument<512> doc; // Adjust size if needed
    DeserializationError error = deserializeJson(doc, file);
    if (error) {
        Serial.println("Failed to parse settings file. Using default relay timings.");
        file.close();
        return;
    }

    // Populate relayDurations array
    for (uint8_t i = 0; i < 16; i++) {
        String key = String("b") + (i + 1);
        if (doc.containsKey(key)) {
            relayDurations[i] = doc[key].as<uint16_t>();
            Serial.printf("Loaded relay %d duration: %d ms\n", i + 1, relayDurations[i]);
        }
    }

    file.close();
}

//
void updateSchedule(JsonDocument doc) {
    const char* fileName = doc["file"];

    // Ensure fileName exists and is valid
    if (!fileName || strlen(fileName) == 0) {
        Serial.println("Invalid JSON payload: Missing or invalid 'file' field");
        return;
    }

    // Serialize the "data" object into a string
    String dataString;
    serializeJson(doc["data"], dataString); // Converts the "data" object to a JSON string

    if (dataString.length() > 0) {
        savefile(fileName, dataString.c_str());
        Serial.printf("File '%s' updated successfully.\n", fileName);
    } else {
        Serial.println("Invalid JSON payload: Unable to serialize 'data'");
    }
		timekeeper.refreshDailySchedule();
}
