#line 1 "C:\\Users\\espi_\\Documents\\Arduino\\4. Bell Systems\\1. Main Projects\\Project - Vesper\\functions.hpp"
#pragma once

extern std::vector<uint16_t> melody_steps;
extern uint16_t relayDurations[16];

void setMelodyAttributes(JsonDocument doc);
void loadMelodyInRAM(std::vector<uint16_t> &melody_steps);
void loadRelayTimings();
void saveRelayTimings();

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

// Sets incoming Attributes for the Melody, into the class' variables.
void setMelodyAttributes(JsonDocument doc){

	if (doc.containsKey("name")) {
			melody.name = doc["name"].as<const char*>();
	}
	if (doc.containsKey("id")) {
			melody.id = doc["id"].as<uint16_t>();
	}
	if (doc.containsKey("duration")) {
			melody.duration = doc["duration"].as<uint32_t>();
	}
	if (doc.containsKey("infinite")) {
			melody.infinite_play = doc["infinite"].as<bool>();
	}
	if (doc.containsKey("interval")) {
			melody.interval = doc["interval"].as<uint32_t>();
	}
	if (doc.containsKey("speed")) {
			melody.speed = doc["speed"].as<uint16_t>();
	}
	if (doc.containsKey("loop_dur")) {
			melody.loop_duration = doc["loop_dur"].as<uint32_t>();
	}
	// Print Just for Debugging Purposes
	Serial.printf("Name: %s, ID: %d, Total Duration: %lu, Loop Duration: %lu, Interval:  %d, Speed: %d, Inf: %s\n",
		melody.name.c_str(),
		melody.id,
		melody.duration,
		melody.loop_duration,
		melody.interval,
		melody.speed,
		melody.infinite_play ? "true" : "false"
		);
}

// Loads the Selected melody from a .bin file, into RAM
void loadMelodyInRAM(std::vector<uint16_t> &melody_steps) {

	std::string filePath = "/" + melody.name + ".bin";
	Serial.println("New Melody Selected !!!");
	Serial.println("Reading data from file...");
	File bin_file = SPIFFS.open(filePath.c_str(), "r");
	if (!bin_file) {
		Serial.println("Failed to Open File");
		return;
	}

	size_t fileSize = bin_file.size();
	size_t steps = fileSize / 2;
	melody_steps.resize(steps);

	Serial.print("Opened File ! Size: ");
	Serial.print(fileSize);
	Serial.print(" Steps: ");
	Serial.println(steps);

	for (size_t i=0; i<steps; i++){
		melody_steps[i] = bin_file.read() << 8 | bin_file.read();
	}

	for (size_t i=0; i<steps; i++){
		Serial.print("Current Step: ");
		Serial.printf("%03d  // ", i);
		Serial.print("  HEX Value: ");
		Serial.printf("0x%04X\n", melody_steps[i]);
	}
	Serial.println("Closing File");
	bin_file.close();

	// closing the file

}

// Sets Incoming Relay Durations to RAM and then call funtion to save them to file.
void setRelayDurations(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();
}

// 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];
    }

    // Open the file for writing
    File file = SPIFFS.open("/settings/relayTimings.json", FILE_WRITE);
    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", FILE_READ);
    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();
}
