#include <WiFi.h>
#include "DHTesp.h"
#include <HTTPClient.h>
#include <RTClib.h>

DHTesp dhtsensor;
RTC_DS3231 rtc;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  pinMode(4, OUTPUT);
  dhtsensor.setup(15, DHTesp::DHT22);
  // initialise the rtc
  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC. Dead now.");
    while(1);
  }
  connectWiFi();
}
  //doSaveData();

String displayDigit (int num) {
  String number = "";
  if (num < 10) {
    number = "0" + String(num);
  }
  else {
    number = String(num);
  }
  return number;
}

void loop() {
  // get the current time and date
  DateTime now = rtc.now();
  String str_time = "Time%3A%20" +     /*Time: */
                    displayDigit(now.hour()) +
                    "%3A" +            /*:*/
                    displayDigit(now.minute()) + 
                    "%3A" +            /*:*/
                    displayDigit(now.second()) + 
                    "%20Date%3A%20" +  /* Date: */
                    displayDigit(now.day()) +
                    "-" + 
                    displayDigit(now.month()) + 
                    "-" + 
                    now.year() ;

  TempAndHumidity data = dhtsensor.getTempAndHumidity();
  Serial.println("Temp:" + String(data.temperature, 2) + "C");
  Serial.println("Humidity:" + String(data.humidity, 1) + "%");
  Serial.println("---");
  String str_temperature = String(data.temperature, 2),str_humidity = String(data.humidity, 1);
  doSaveData(str_time, str_temperature, str_humidity);
  doLoadData();
  delay(100); // this speeds up the simulation
}

void connectWiFi() {
  Serial.print("Connecting to WiFi");
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");
}

void doSaveData(String str_time, String t, String h) {
  Serial.println("doSaveData!");
  String id = "AKfycbyXaTazpj1yAhm_ENHCdCvH3WLxtS_xab-1ISbFt5QwcnNcjZuDVPQp_eia35JD16-m";
  String url = "https://script.google.com/macros/s/"+ id + "/exec?time="+str_time+"&sensor=溫溼度&value=" + t + "%2F" + h;
  HTTPClient http;
  http.begin(url);
  
  int httpCode = http.GET();
  Serial.println(httpCode);
  // String payload =http.getString();
  // Serial.println(payload);
  http.end();
}

void doLoadData() {
  Serial.println("doLoadData!");
  String id = "AKfycbyXaTazpj1yAhm_ENHCdCvH3WLxtS_xab-1ISbFt5QwcnNcjZuDVPQp_eia35JD16-m";
  String url = "https://script.google.com/macros/s/"+ id + "/exec?load";
  HTTPClient http;
  http.begin(url);
  http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
  int httpCode = http.GET();
  Serial.println(httpCode);
  String payload = http.getString();
  Serial.println(payload);
  http.end();
}
GND5VSDASCLSQWRTCDS1307+