#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();
}

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 = "%20Time%3A%20"+ displayDigit(now.hour()) +
                    "%3A" + displayDigit(now.minute()) +
                    "%3A" + displayDigit(now.second()) +
                    "%20Date%3A%20" + 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);
  String str_humidity = String(data.humidity,1);
  doSaveData(str_time, str_temperature, str_humidity);
  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!");
}

void doSaveData(String str_time, String str_temperature, String str_humidity) {
  Serial.println("doSaveData!");
  String id = "AKfycbwVqJStZasLhAar2TKKU7vBNA9hhIJWHWKBOJ23D2_5vourgg6JJ4wOWl-EKf2Fcrl8";
  String url = "https://script.google.com/macros/s/"+id+"/exec?time="+ str_time +"&sensor=溫溼度&value="+str_temperature +"%2F"+ str_humidity;
  HTTPClient http;
  http.begin(url);
  int httpCode = http.GET();
  Serial.println(httpCode);
  http.end();
}

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