#include "../include/API.h"


API::API(String user, String password, String host, bool https){
    this->user = user;
    this->password = password;
    this->serveurHost = host;
    this->https = https;
    this->token = "";
    this->client = new WiFiEspClient();
}


bool API::wifiBegin(String wifiId, String wifiPass, Stream* espSerial){
    WiFi.init(espSerial);

    // check for the presence of the shield
    if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");  // FIXME: rm debug
        return false;
    }

    // attempt to connect to WiFi network
    int status = WL_IDLE_STATUS;      // the Wifi radio's status
    while (status != WL_CONNECTED) {
        status = WiFi.begin(wifiId.c_str(), wifiPass.c_str());
    }
    return true;
}
bool API::connect(){
    this->client->stop();
    bool sortie = false;

    JSONVar data;

    data["identity"] = this->user;
    data["password"] = this->password;

    String strData = JSONVar::stringify(data);

    if(this->https){
        if (!this->client->connectSSL(this->serveurHost.c_str(), 443)) {
            Serial.println("NOT Connected to server");
            return sortie;
        }
    }else{
        if (!this->client->connectSSL(("http://" + this->serveurHost).c_str(), 80)) {
            Serial.println("NOT Connected to server");
            return sortie;
        }
    }
    this->client->println("POST /api/collections/users/auth-with-password HTTP/1.1");
    this->client->println("Host: " + this->serveurHost);
    this->client->println("Content-Type: application/json");
    this->client->println("Content-Length: " + String(strData.length()));
    this->client->println();
    this->client->println(strData);
    this->client->println("Connection: close");
    this->client->println();


    while (!client->available()) {}

    String responce = "";
    while (client->available()) {
        responce += (char)client->read();
    }

    String str = responce.substring(responce.indexOf("{"),responce.lastIndexOf("}")+1);

    JSONVar jsonRes =  new JSONVar(JSONVar::parse(str));

    this->token = JSONVar::stringify(jsonRes["token"]);

    this->token = this->token.substring(1,this->token.length()-1);
    
    this->client->stop();
    
    sortie = true;

    return sortie;
}

bool API::sendValute(String val, String poubelleID, String valUnit, bool full){
    JSONVar data;
    data["value"] = val;
    data["trash_id"] = poubelleID;
    data["unit"] = valUnit;
    data["status"] = full;

    String strData = JSONVar::stringify(data);

    if(this->token == ""){
        bool connected = this->connect();
        if(!connected)return false;
    }
    if(this->https){
        if (!this->client->connectSSL(("https://" + this->serveurHost).c_str(), 443)) {
            Serial.println("NOT Connected to server");
            return false;
        }
    }else{
        if (!this->client->connectSSL(("http://" + this->serveurHost).c_str(), 80)) {
            Serial.println("NOT Connected to server");
            return false;
        }
    }
    this->client->println("POST /api/collections/data/records HTTP/1.1");
    this->client->println("Host: " + this->serveurHost);
    this->client->println("Content-Type: application/json");
    this->client->println("Content-Length: " + String(strData.length()));
    this->client->println("Authorization: Bearer " + this->token);
    this->client->println();
    this->client->print(strData);
    this->client->println("Connection: close");
    this->client->println();

    this->token = "";//XXX: on rm le token a chaque fois car on sais pas si la requet a bien aboutie et donc si il y est encore bon
    return true;
}