//Include required libraries
#include "WiFi.h"
#include <HTTPClient.h>
#include <time.h>
#include <sys/time.h>

// WiFi credentials
const char* ssid = "Wokwi-GUEST";         // change SSID
const char* password = "";    // change password

// Google script ID and required credentials
const String GOOGLE_SCRIPT_ID = "AKfycbyk3ZyvO5oIM1tvtUvSMnUxFXUCVSk0Yoz0YPCK-qiWGMjluPXrpWjfvqynuosIube_";    // change Gscript ID
const int EVENT_OPEN = 1;
const int EVENT_CLOSE = 0;
const String EVENT_NAME = "door_sensor_1";

String event_string = "";
bool last_state = false;
bool current_state = false;
bool server_free = true;

int retry_counter = 0;

void setup() {
  pinMode(4, INPUT_PULLUP);
  delay(100);
  Serial.begin(115200);
  delay(100);

  // connect to WiFi
  Serial.println();
  Serial.print("Connecting to WiFi: ");
  Serial.println(ssid);
  Serial.flush();
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("Connected to WiFi");
}

void loop() {
  if (Serial.available() > 0) {
    char command = Serial.read();

    if (command == '1') {
      event_string = String(EVENT_OPEN);
      Serial.println("*** Simulando abertura da porta ***");
    } else if (command == '2') {
      event_string = String(EVENT_CLOSE);
      Serial.println("*** Simulando fechamento da porta ***");
    }

    if (server_free) {
      server_free = false;
      xTaskCreate(post_data, "post_data", 7168, nullptr, 4, nullptr);
    } else {
      Serial.println("*** HTTP SERVER OCUPADO! IGNORANDO EVENTO ***");
    }
  }
  delay(50); // debounce
}

void post_data(void* params) {
  retry_counter = 3;
  
  while (retry_counter > 0) {
   /* String urlFinal = "https://script.google.com/macros/s/" + GOOGLE_SCRIPT_ID +
                      "/exec?" + EVENT_NAME + "=" + event_string +
                      "&retries_left=" + String(retry_counter) +
                      "&esp_time=" + String(millis()); */

   String urlFinal = "https://script.google.com/macros/s/" + GOOGLE_SCRIPT_ID +
                      "/exec?timestamp=" + String(millis());

    Serial.println("Enviando dados para a planilha:");
    Serial.println(urlFinal);
    
    HTTPClient http;
    http.begin(urlFinal.c_str());
    http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
    int httpCode = http.GET();
    
    Serial.print("Código de status HTTP: ");
    Serial.println(httpCode);

    // Obtendo resposta da planilha do Google
    if (httpCode > 0) {
      String payload;
      payload = http.getString();
      Serial.println("Resposta: " + payload);
      http.end();
      retry_counter = 0;
    } else {
      retry_counter--;
      Serial.println("HTTP GET falhou - tentativas restantes: " + String(retry_counter));
      delay(2000);
    }
  }

  server_free = true;
  vTaskDelete(nullptr);
}