#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <Adafruit_MPU6050.h>
#include <UniversalTelegramBot.h>
#include <DHTesp.h>

DHTesp dhtSensor;
TempAndHumidity data;
const int DHT_PIN=25;

// https://randomnerdtutorials.com/telegram-control-esp32-esp8266-nodemcu-outputs/

#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// 
#define BOTtoken "6397268428:AAGjUkF7tau80d6o73WcuYPdUfzirIutqUI"  
// your Bot Token (Get from Botfather)
#define CHAT_ID "192973085"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

// Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

const int ledPin = 2;
bool ledState = LOW;

String getReadings(){
    data=dhtSensor.getTempAndHumidity();
  String message = "Temperature: " + String(data.temperature) + " ºC \n";
  message += "Humidity: " + String (data.humidity) + " % \n";
  return message;
}

//Handle what happens when you receive new messages
void handleNewMessages(int numNewMessages) {
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));

  for (int i=0; i<numNewMessages; i++) {
    // Chat id of the requester
    String chat_id = String(bot.messages[i].chat_id);
    if (chat_id != CHAT_ID){
      bot.sendMessage(chat_id, "Unauthorized user", "");
      continue;
    }
    
    // Print the received message
    String text = bot.messages[i].text;
    Serial.println(text);

    String from_name = bot.messages[i].from_name;

    if (text == "/start") {
      String welcome = "Welcome, " + from_name + ".\n";
      welcome += "Use the following command to get current readings.\n\n";
      welcome += "/readings \n";
      bot.sendMessage(chat_id, welcome, "");
    }

    if (text == "/readings") {
      String readings = getReadings();
      bot.sendMessage(chat_id, readings, "");
    }  
  }
}


const int LED1 = 26;
const int LED2 = 27;
const int trig = 13;
const int echo = 12;

bool led1State = false;
bool led2State = false;


void setup(void) {
  Serial.begin(115200);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  digitalWrite(LED1, ledState);
  // ultrasonic
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);

  dhtSensor.setup(DHT_PIN,DHTesp::DHT22);

  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to WiFi ");
  Serial.print(WIFI_SSID);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  #ifdef ESP32
    client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  #endif
 
  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());

}

void loop(void) {
  digitalWrite(trig, LOW);
  delayMicroseconds(10);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  int durasi = pulseIn(echo,HIGH);
  int jarak = durasi * 0.034 /2;

  Serial.println(jarak);

  if (millis() > lastTimeBotRan + botRequestDelay)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    lastTimeBotRan = millis();
  }
}