/* ESP32 WiFi Scanning example */
#define _DISABLE_TLS_
#include "config.h"
#include "my_wifi.h"
#include <DHTesp.h>
#include "wifi_communicator.h"

#define ENABLE_DEBUG
#include <MacroDebugger.h>

DHTesp dht;
#define DHT_PIN 15

// Communication messages
char incoming_msg[MAX_BUFFER_LEN] = {0};
char response[MAX_BUFFER_LEN] = {0};

/* A collection of random responses to send when the button is clicked */
#define NUM_RANDOM_RESPONSES    10
char *responses[NUM_RANDOM_RESPONSES] = {
  "hola!",
  "hiii",
  "potato",
  "arduino",
  "esp32",
  "okay so we get it it's a random message!",
  "so what?",
  "running out of messages here",
  "okay two more to go",
  "finally ..."
};

void setup(){
  Serial.begin(115200);

  DEBUG_BEGIN();
  
  setup_wifi();
  
  setup_wifi_communicator();

  // pinMode(LED_PIN, OUTPUT);
  dht.setup(DHT_PIN, DHTesp::DHT22);
  DEBUG_I("Done setting up!");
}

void loop(){
  // if we lost connection, we attempt to reconnect (blocking)
  if(!is_client_connected()){ connect_client(); }

  bool received = get_message(incoming_msg);

  if(received){
    DEBUG_I("Received: %s", incoming_msg);
    // Serial.print(incoming_msg);
    uint8_t start = 0;

    if(incoming_msg[0] == 'A'){
      sprintf(response, "%s", ACK);
      start++;
    }

    // If start is bigger than 0, then we have to acknowledge the reception
    if(start > 0){
      send_message(response);
      // Clear the response buffer
      memset(response, 0, MAX_BUFFER_LEN);
    }
  }
  // delay(1500);
  if(dht.getTemperature() > 38){
    uint8_t idx = random(NUM_RANDOM_RESPONSES);
    strncpy(response, responses[idx], MAX_BUFFER_LEN);
    send_message(response);
    memset(response, 0, MAX_BUFFER_LEN);
    DEBUG_I("Sent: %s", responses[idx]);

    Serial.print(dht.getTemperature());
  }
}

// #include "WiFi.h"

// #define SSID "Wokwi-GUEST"
// #define SSID_PASSWORD ""

// DHTesp dht;
// #define DHT_PIN 15
// void setup() {
//  Serial.begin(115200);

//  InitWiFi();
//  dht.setup(DHT_PIN, DHTesp::DHT22);
// }

// void loop() {
//   Serial.print(dht.getTemperature());
// }

// void InitWiFi() {
//  Serial.println("Connecting to WiFi ...");
//  // attempt to connect to WiFi network
//  WiFi.begin(SSID, SSID_PASSWORD);

//  while (WiFi.status() != WL_CONNECTED) {
//   delay(500);
//   Serial.print(".");
//  }

//  Serial.println("Connected to WiFi");
// }