//Negro = pin1(conector original)
//Rojo = pin3(conector original)
//Blanco = pin4(conector original)
//Verde = pin5(conector original)

#include "WiFi.h"
#include <HTTPClient.h>
#include "time.h"
#include "HX711.h"

const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 19800;
const int dayligthOffset_sec = 0;

//const char* ssid = "Empeco-inv";
//const char* pass = "Empeco21#";

String GOOGLE_SCRIPT_ID = "AKfycbxHkOgKOwOs0HGMuoNwIPqzn2SpO7IfQ-GBM5cOddm-vIS4WMjUGFUawSfpnfm_IMqS";

const int LOADCELL_DOUT_PIN = 19;
const int LOADCELL_SCK_PIN = 18;
HX711 balanza;

void setup()
{  Serial.begin(115200);
   balanza.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
   delay(250);

   balanza.set_scale(21.460665);
   balanza.tare(10);  // Hacer 10 lecturas, el promedio es la tara

   Serial.println();
   Serial.print("Conectado a WiFi: ");
   Serial.println("Wokwi-GUEST");
   Serial.flush();
   WiFi.begin("Wokwi-GUEST", "", 6);
   while (WiFi.status() != WL_CONNECTED)
   {
    delay(500);
    Serial.print(".");
   }
   configTime(gmtOffset_sec, dayligthOffset_sec, ntpServer);  
}

void loop()
{  
  if(WiFi.status() == WL_CONNECTED)
  {
    static bool flag = false;
    struct tm timeinfo;
    if(!getLocalTime(&timeinfo))
    {
      Serial.println("Fallo en obtener el tiempo");
      return;
    }
    char timeStringBuff[50];
    strftime(timeStringBuff, sizeof(timeStringBuff), "%A,%B %d %Y %H:%M:%S", &timeinfo);
    String asString(timeStringBuff);
    asString.replace(" ", "-");
    Serial.print("Time: ");
    Serial.println(asString);
      
      float reading;
      if (balanza.is_ready())
     {
      reading = balanza.get_units(10);
       Serial.println(reading  );
     }
   else
   {
       Serial.println("HX711 not found.");
   delay(500);
   }
    String r = String(reading,2);
    
    String urlP = "https://script.google.com/macros/s/AKfycbxHkOgKOwOs0HGMuoNwIPqzn2SpO7IfQ-GBM5cOddm-vIS4WMjUGFUawSfpnfm_IMqS/exec?";
    String urlPP = urlP + "date=";
    String urlPPP = urlPP + asString;
    String urlPPPP = urlPPP + "&sensor=";
    String urlFinal = urlPPPP + r;
    
    Serial.print("Posteando datos en la hoja de datos");
    Serial.println(urlFinal);
    HTTPClient http;
    http.begin(urlFinal.c_str());
    http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
    int httpCode = http.GET();
    Serial.print("HTTP Status Code: ");
    Serial.println(httpCode);

     String payload; 
     if (httpCode > 0)
     {
      payload = http.getString();
      Serial.println("Payload: " + payload);
     }
     http.end();
  }  

}