#ifdef ESP32
  #include <WiFi.h>
#else
  #include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>   // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>

// Replace with your network credentials
const char* ssid = "iPhone";
const char* password = "12345678";

// Initialize Telegram BOT
#define BOTtoken "6896699623:AAGe4gVd4h7AuU9lIjBtdfshHywPprd5tCw"  // your Bot Token (Get from Botfather)

// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you

#define CHAT_ID "-1002080470995"

#ifdef ESP8266
  X509List cert(TELEGRAM_CERTIFICATE_ROOT);
#endif

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

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

const int ledPin = 15;
const int Sensor = 23;
bool ledState = LOW;
bool autoLig = false;


// 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 == "Ola") {
      String welcome = "Olá, "  + from_name + ".\n";
      welcome += "Você pode usar os seguintes comandos para controlar a saída.\n\n";
      welcome += "Ligar \n";
      welcome += "Desligar \n";
      welcome += "Sensor \n";
      welcome += "Estado \n";
      welcome += "Ligar automático \n";
      welcome += "Desligar automático \n";
      bot.sendMessage(chat_id, welcome, "");
    }

    if (text == "Ligar") {
      bot.sendMessage(chat_id, "Ligado", "");
      ledState = HIGH;
      digitalWrite(ledPin, ledState);
    }
    
    if (text == "Desligar") {
      bot.sendMessage(chat_id, "Desligado", "");
      ledState = LOW;
      digitalWrite(ledPin, ledState);
    }

//Verificação 1
        if (text == "Estado") {
      if (digitalRead(ledPin)){
        bot.sendMessage(chat_id, "Ligado", "");
      }
      else{
        bot.sendMessage(chat_id, "Desligado", "");
      }
    }

//Verificação 2
    if (text == "Sensor") {
      if (digitalRead(Sensor)){
       //1
       bot.sendMessage(chat_id, "Seco", "");
      }
      else{
       //0
       bot.sendMessage(chat_id, "Molhado", "");
      }
    }

//ligar o automático
    if(autoLig == false && text == "Ligar automático"){
     bot.sendMessage(chat_id, "Automático ligado", "");
     autoLig = true;
    }
//desligar o automático
    if(autoLig == true && text == "Desligar automático"){
     bot.sendMessage(chat_id, "Automático desligado", "");
     autoLig = false;
    }

//definir o estado do led com o digitalread do sensor
     if (autoLig == true && !digitalRead(Sensor)){
      //0
      ledState = HIGH;
      digitalWrite(ledPin, ledState);
     }

  
  
  }
}

void setup() {
  Serial.begin(115200);

  #ifdef ESP8266
    configTime(0, 0, "pool.ntp.org");      // get UTC time via NTP
    client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
  #endif

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
  
  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  #ifdef ESP32
    client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  #endif
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());
}

void loop() {
  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();
  }
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK