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mNdZ/59pt7lMkV6YDR2\n"\
"pOPnPjqG16TQ7ju2iYonhoHPd/iWs7iKcBs8/eaMYxcpqQDbX+O6hN5qPcTBfGRB\n"\
"TFqwgSu0abNIZ3IJuSUGxkoPcIxNWLTxnwCgUN+TQTrg6rWw8T7GtSzKBljVk09R\n"\
"9YmKHPhUN7wjNRzWiecfomTi3FTgYbrzbwCSTj3FAogCxuHAwA==\n"\
"-----END CERTIFICATE-----\n";

Tahoma::Tahoma(const String _hostname, const String _token) : connected(false) {
    hostname = _hostname;
    token = _token;
}

// Destructor
Tahoma::~Tahoma() {
    
}

String url_encode(const String &value) {
    String escaped;

    for (uint16_t i = 0; i < value.length(); i++) {
        
        char c = value.charAt(i);
        // Keep alphanumeric and other accepted characters intact
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped += c;
            continue;
        }else{
            // Any other characters are percent-encoded
            if(c < 0x10){
                escaped += "%0" + String(c, HEX);
            }else{
                escaped += '%' + String(c, HEX);
            }
        }
    }

    return escaped;
}

String Tahoma::getDeviceName(const String _url)
{
    //String url = "/enduser-mobile-web/1/enduserAPI/apiVersion"; // Construct the URL to fetch the device name
    HTTPClient http; // Create an HTTP client object
    String url = "/enduser-mobile-web/1/enduserAPI/setup/devices/" + url_encode(_url) + "/states/core:NameState"; // Construct the URL to fetch the device name
    String deviceName;
    http.begin("1215-2900-8489.local",8443,url,rootCACertificate); // Initialize the HTTP connection
    http.addHeader("Authorization", "Bearer " + token); // Add the authorization header with the token
    int httpCode = http.GET(); // Send the GET request and get the response code
    if (httpCode > 0) { // Check if the request was successful
        JsonDocument doc; // Create a JSON document to parse the response
        String response = http.getString(); // Get the response as a string
        deserializeJson(doc,response); // Deserialize the JSON response 
        Serial.println(response); // Print the response to the serial monitor for debugging
        if (doc["value"].isNull()) { // Check if the value is null
            Serial.println("Device not found"); // Print error message if the device is not found
        }else{
            deviceName = doc["value"].as<String>(); // Get the device name from the JSON response
            Serial.println("Device Name: " + deviceName); // Print the device name to the serial monitor
        }
    } else {
        Serial.print("Error on HTTP request:"); // Print error message if the request failed
        Serial.println(httpCode); // Print the error code
        Serial.print("Error message: "); // Print error message
        Serial.println(http.errorToString(httpCode)); // Print the error code
        Serial.println(url); // Print the URL for debugging
    }
    http.end(); // Close the HTTP connection
    return deviceName; // Return the device name
}


void Tahoma::getAllDevices(void){
    HTTPClient http; // Create an HTTP client object
    String url = "/enduser-mobile-web/1/enduserAPI/setup/devices/controllables/io%3AExteriorVenetianBlindIOComponent"; // Construct the URL to fetch all devices
    http.begin("1215-2900-8489.local",8443,url,rootCACertificate); // Initialize the HTTP connection
    http.addHeader("Authorization", "Bearer " + token); // Add the authorization header with the token
    int httpCode = http.GET(); // Send the GET request and get the response code
    if (httpCode > 0) { // Check if the request was successful
        JsonDocument doc; // Create a JSON document to parse the response
        String response = http.getString(); // Get the response as a string
        deserializeJson(doc,response); // Deserialize the JSON response 
        if(doc.size() > 0){ // Check if the JSON document is not empty
            for (int i = 0; i < doc.size(); i++) { // Loop through the JSON array
                devicelist[i].url = doc[i].as<String>(); // Get the device URL from the JSON response
                Serial.println("Device URL: " + devicelist[i].url); // Print the device URL to the serial monitor
            }
        }
    } else {
        Serial.print("Error on HTTP request:"); // Print error message if the request failed
        Serial.println(httpCode); // Print the error code
        Serial.print("Error message: "); // Print error message
        Serial.println(http.errorToString(httpCode)); // Print the error code
    }
    http.end(); // Close the HTTP connection
}
void Tahoma::getAllDeviceNames(void){
    for (int i = 0; i < MAX_NUM_DEVICES; i++) { // Loop through the JSON array
        if(devicelist[i].url == ""){ // Check if the device URL is empty
            break; // Break the loop if the device URL is empty
        }
        devicelist[i].name = getDeviceName(devicelist[i].url); // Get the device name using the device URL
    }

}