#include <WiFi.h>
#include "DHTesp.h"
#include <HTTPClient.h>
#include <RTClib.h>
RTC_DS3231 rtc;
DHTesp dhtSensor;

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

void loop() {
    TempAndHumidity  data = dhtSensor.getTempAndHumidity();
    Serial.println("Temp: " + String(data.temperature, 2) + "°C");
    Serial.println("Humidity: " + String(data.humidity, 2) + "%");
    Serial.println("-----------------------");
    String str_temperature, str_humidity;
    str_temperature = String(data.temperature, 2)+ "°C";
    str_humidity = String(data.humidity, 1)+ "°%25";
    DateTime now = rtc.now();
    String str_time = "Time%3A%20" + 
                    displayDigit(now.hour()) +
                    "%3A" + 
                    displayDigit(now.minute()) + 
                    "%3A" +
                    displayDigit(now.second()) + 
                    "%20Date%3A%20" +
                    displayDigit(now.day()) +
                    "-" + 
                    displayDigit(now.month()) + 
                    "-" + 
                    now.year() ;
    doSaveData(str_time, str_temperature, str_humidity);
    doLoadData();
    delay(1000); // 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!");
}

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

void doSaveData(String str_time, String t, String h) {
  Serial.println("doSaveData!");
  String id = "AKfycbyGMb7ZqRxZkNGmzQCNmcOysdlzQlbAahJ1CZqw1OcvPQ3TwL9MWnYyarbQJdZeKKUk";
  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);
  http.end();
}

void doLoadData() {
  Serial.println("doLoadData!");
  String id = "AKfycbyGMb7ZqRxZkNGmzQCNmcOysdlzQlbAahJ1CZqw1OcvPQ3TwL9MWnYyarbQJdZeKKUk";
  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+