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

WiFiClient wiFiClient;
PubSubClient client(wiFiClient);
DHTesp dhtsensor;

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

void loop() {
  // put your main code here, to run repeatedly:
  while(!client.connected()){
      if(client.connect("tkuiot1122"+random(0xffff),"tkuiot1122" ,"tkuiot1122")) {
        client.subscribe("tkuiot1122/ta");
      }
  }
  client.loop();
  delay(10); // 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 connectMQTT(){
  client.setServer("connmqttlab.jed.tw", 1883);
  client.setCallback(callback);
}

void callback(char* topic, byte* message, unsigned int length) {
  String strMessage;
  for(int i=0; i<length; i++){
    strMessage += (char)message[i];
  }
  Serial.println(topic);
  Serial.println(strMessage);

  if ( strMessage == "on" ) {
    digitalWrite(4, HIGH);
  } else if ( strMessage == "off" ) {
    digitalWrite(4, LOW);
  } else if ( strMessage == "get" ) {
    TempAndHumidity data = dhtsensor.getTempAndHumidity();
    Serial.println("Temp:");
    Serial.println(data.temperature);
    Serial.println("Humidity:");
    Serial.println(data.humidity);
    String temperature = "Temperature:" + String(data.temperature, 2) + "C"; // Ans
    String humidity = ",Humidity:" + String(data.humidity, 2) + "%";         // Ans
    String resp = temperature + humidity;                                    // Ans
    client.publish("tkuiot1122/ta", (char*)resp.c_str());                    // Ans
  } else if ( strMessage == "save" ) {
    TempAndHumidity data = dhtsensor.getTempAndHumidity();
    Serial.println("Temp:");
    Serial.println(data.temperature);
    Serial.println("Humidity:");
    Serial.println(data.humidity);
    String temperature = "Temperature%3A" + String(data.temperature, 2) + "C"; // Ans
    String humidity = "%2CHumidity%3A" + String(data.humidity, 2) + "%25";         // Ans
    String resp = temperature + humidity;                                    // Ans
    //client.publish("tkuiot1112/ta", (char*)resp.c_str());                    // Ans
    doSaveData(resp);
  } else if ( strMessage == "load" ) {
    doLoadData();
  }

}

void doLoadData() {
  Serial.println("doLoadData!");
  String id = "AKfycbx93TeGyseqyhDFa6hPw3sXenTetrUiDykiB4lVb62ZDXF7EkjZP5iAlIt3hD7OAwYi4Q";
  String url = "https://script.google.com/macros/s/"+id+"/exec?read";
  HTTPClient http;
  http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
  http.begin(url);
  int httpCode = http.GET(); // need fast tls
  String payload;
  if (httpCode > 0) { //Check for the returning code
    payload = http.getString();
    Serial.println(httpCode);
    Serial.println(payload);
  }
  else {
    Serial.println("Error on HTTP request");
  }
  http.end();
}


void doSaveData(String sensor_data) {
  Serial.println("doSaveData!");
  Serial.println(sensor_data);
  String id = "AKfycbx93TeGyseqyhDFa6hPw3sXenTetrUiDykiB4lVb62ZDXF7EkjZP5iAlIt3hD7OAwYi4Q";
  String url = "https://script.google.com/macros/s/"+id+"/exec?sensor=DHT"+"&date=456"+"&value="+sensor_data;
  HTTPClient http;
  http.begin(url);
  int httpCode = http.GET();
  Serial.println(httpCode);
  http.end();
}