#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "esp_camera.h"
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <TimeLib.h>
#include "Countimer.h"
#include <ESP32Servo.h>

#define servopin1 15

Servo Servo1;

const char* ssid = "OPPOA53";
const char* password = "tahu1234";

// Initialize Telegram BOT
String BOTtoken = "5704579251:AAEJgW1070v6MzBPEcQOAO662YJatjvjFkU";  // 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
String CHAT_ID = "1654333204";
Countimer tdown1, tdown2, tdown3, tdown4, tdown5;
int maxday[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int detik = 25;
int menit = 15;
int jam = 9;
int tanggal = 13;
int bulan = 1;
int tahun = 2023;

int set_detik1 = 30;
int set_menit1 = 2;
int set_jam1 = 0;
int last_set_detik1 = 0;
int last_set_menit1 = 0;
int last_set_jam1 = 0;

int set_detik2 = 0;
int set_menit2 = 5;
int set_jam2 = 0;
int last_set_detik2 = 0;
int last_set_menit2 = 0;
int last_set_jam2 = 0;

int set_detik3 = 30;
int set_menit3 = 7;
int set_jam3 = 0;
int last_set_detik3 = 0;
int last_set_menit3 = 0;
int last_set_jam3 = 0;

int set_detik4 = 0;
int set_menit4 = 10;
int set_jam4 = 0;
int last_set_detik4 = 0;
int last_set_menit4 = 0;
int last_set_jam4 = 0;

int set_detik5 = 30;
int set_menit5 = 12;
int set_jam5 = 0;
int last_set_detik5 = 0;
int last_set_menit5 = 0;
int last_set_jam5 = 0;

bool timer1 = false;
bool timer2 = false;
bool timer3 = false;
bool timer4 = false;
bool timer5 = false;
bool gerak = false;
bool sendPhoto = false;

WiFiClientSecure clientTCP;
UniversalTelegramBot bot(BOTtoken, clientTCP);

#define FLASH_LED_PIN 4
bool flashState = LOW;

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

//CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

void configInitCamera() {
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_4;
  config.ledc_timer = LEDC_TIMER_2;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  
  config.frame_size = FRAMESIZE_VGA;
  config.jpeg_quality = 10;
  config.fb_count = 1;

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    delay(1000);
    ESP.restart();
  }

  // Drop down frame size for higher initial frame rate
  sensor_t * s = esp_camera_sensor_get();
  s->set_framesize(s, FRAMESIZE_CIF);  // UXGA|SXGA|XGA|SVGA|VGA|CIF|QVGA|HQVGA|QQVGA
}

void handleNewMessages(int numNewMessages) {
  Serial.print("Handle New Messages: ");
  Serial.println(numNewMessages);

  for (int i = 0; i < numNewMessages; i++) {
    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 commands to interact with the ESP32-CAM \n";
      welcome += "/photo  : takes a new photo\n";
      welcome += "/flash  : toggles flash LED\n";
      welcome += "/5menit : mengetching pcb selama 5 menit\n";
      welcome += "/10menit : mengetching pcb selama 10 menit\n";
      welcome += "/15menit : mengetching pcb selama 15 menit\n";
      welcome += "/20menit : mengetching pcb selama 20 menit\n";
      welcome += "/25menit : mengetching pcb selama 25 menit\n";
      bot.sendMessage(CHAT_ID, welcome, "");
    }
    if (text == "/flash") {
      flashState = !flashState;
      digitalWrite(FLASH_LED_PIN, flashState);
      Serial.println("Change flash LED state");
    }
    if (text == "/photo") {
      sendPhoto = true;
      Serial.println("New photo request");
    }
    if (text == "/5menit") {
      bot.sendMessage(chat_id, "Okay, Mengetching pcb selama 5 menit");
      timer1 = true;
      timer2 = false;
      timer3 = false;
      timer4 = false;
      timer5 = false;
      gerak = true;
      tdown1.setInterval(print_time1, 50);
      delay(50);
    }
    if (text == "/10menit") {
      bot.sendMessage(chat_id, "Okay, Mengetching pcb selama 10 menit");
      timer1 = false;
      timer2 = true;
      timer3 = false;
      timer4 = false;
      timer5 = false;
      gerak = true;
      tdown2.setInterval(print_time2, 50);
      delay(50);
    }
    if (text == "/15menit") {
      bot.sendMessage(chat_id, "Okay, Mengetching pcb selama 15 menit");
      timer1 = false;
      timer2 = false;
      timer3 = true;
      timer4 = false;
      timer5 = false;
      gerak = true;
      tdown3.setInterval(print_time3, 50);
      delay(50);
    }
    if (text == "/20menit") {
      bot.sendMessage(chat_id, "Okay, Mengetching pcb selama 20 menit");
      timer1 = false;
      timer2 = false;
      timer3 = false;
      timer4 = true;
      timer5 = false;
      gerak = true;
      tdown4.setInterval(print_time4, 50);
      delay(50);
    }
    if (text == "/25menit") {
      bot.sendMessage(chat_id, "Okay, Mengetching pcb selama 25 menit");
      timer1 = false;
      timer2 = false;
      timer3 = false;
      timer4 = false;
      timer5 = true;
      gerak = true;
      tdown5.setInterval(print_time5, 50);
      delay(50);
    }
  }
}

String sendPhotoTelegram() {
  const char* myDomain = "api.telegram.org";
  String getAll = "";
  String getBody = "";

  camera_fb_t * fb = NULL;
  fb = esp_camera_fb_get();
  if (!fb) {
    Serial.println("Camera capture failed");
    delay(100);
    ESP.restart();
    return "Camera capture failed";
  }

  Serial.println("Connect to " + String(myDomain));


  if (clientTCP.connect(myDomain, 443)) {
    Serial.println("Connection successful");

    String head = "--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"chat_id\"; \r\n\r\n" + CHAT_ID + "\r\n--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
    String tail = "\r\n--RandomNerdTutorials--\r\n";

    uint16_t imageLen = fb->len;
    uint16_t extraLen = head.length() + tail.length();
    uint16_t totalLen = imageLen + extraLen;

    clientTCP.println("POST /bot" + BOTtoken + "/sendPhoto HTTP/1.1");
    clientTCP.println("Host: " + String(myDomain));
    clientTCP.println("Content-Length: " + String(totalLen));
    clientTCP.println("Content-Type: multipart/form-data; boundary=RandomNerdTutorials");
    clientTCP.println();
    clientTCP.print(head);

    uint8_t *fbBuf = fb->buf;
    size_t fbLen = fb->len;
    for (size_t n = 0; n < fbLen; n = n + 1024) {
      if (n + 1024 < fbLen) {
        clientTCP.write(fbBuf, 1024);
        fbBuf += 1024;
      }
      else if (fbLen % 1024 > 0) {
        size_t remainder = fbLen % 1024;
        clientTCP.write(fbBuf, remainder);
      }
    }

    clientTCP.print(tail);

    esp_camera_fb_return(fb);

    int waitTime = 10000;   // timeout 10 seconds
    long startTimer = millis();
    boolean state = false;

    while ((startTimer + waitTime) > millis()) {
      Serial.print(".");
      delay(1000);
      while (clientTCP.available()) {
        char c = clientTCP.read();
        if (state == true) getBody += String(c);
        if (c == '\n') {
          if (getAll.length() == 0) state = true;
          getAll = "";
        }
        else if (c != '\r')
          getAll += String(c);
        startTimer = millis();
      }
      if (getBody.length() > 0) break;
    }
    clientTCP.stop();
    Serial.println(getBody);
  }
  else {
    getBody = "Connected to api.telegram.org failed.";
    Serial.println("Connected to api.telegram.org failed.");
  }
  return getBody;
}

void setup() {
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  // Init Serial Monitor
  Serial.begin(115200);
  Servo1.attach(servopin1);
  // Set LED Flash as output
  pinMode(FLASH_LED_PIN, OUTPUT);
  digitalWrite(FLASH_LED_PIN, flashState);

  // Config and init the camera
  configInitCamera();

  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  setTime(jam, menit, detik, tanggal, bulan, tahun);
  Serial.println();
  Serial.print("ESP32-CAM IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  tdown1.run();
  tdown2.run();
  tdown3.run();
  tdown4.run();
  tdown5.run();

  if (sendPhoto) {
    Serial.println("Preparing photo");
    sendPhotoTelegram();
    sendPhoto = false;
  }
  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();
  }
  if (timer1 == true) {
    tdown1.start();
    if (set_detik1 == 0 && set_menit1 == 0 && set_jam1 == 0) {
      tdown1.stop();
      sendPhoto = true;
      timer1 = false;
      timer2 = false;
      timer3 = false;
      timer4 = false;
      timer5 = false;
      gerak = false;
      set_detik1 = 30;
      set_menit1 = 2;
      set_jam1 = 0;
      last_set_detik1 = 0;
      last_set_menit1 = 0;
      last_set_jam1 = 0;
    }
  }
  if (timer2 == true) {
    tdown2.start();
    if (set_detik2 == 0 && set_menit2 == 0 && set_jam2 == 0) {
      tdown2.stop();
      sendPhoto = true;
      timer1 = false;
      timer2 = false;
      timer3 = false;
      timer4 = false;
      timer5 = false;
      gerak = false;
      set_detik2 = 0;
      set_menit2 = 5;
      set_jam2 = 0;
      last_set_detik2 = 0;
      last_set_menit2 = 0;
      last_set_jam2 = 0;
    }
  }
  if (timer3 == true) {
    tdown3.start();
    if (set_detik3 == 0 && set_menit3 == 0 && set_jam3 == 0) {
      tdown3.stop();
      sendPhoto = true;
      timer1 = false;
      timer2 = false;
      timer3 = false;
      timer4 = false;
      timer5 = false;
      gerak = false;
      set_detik3 = 30;
      set_menit3 = 7;
      set_jam3 = 0;
      last_set_detik3 = 0;
      last_set_menit3 = 0;
      last_set_jam3 = 0;
    }
  }
  if (timer4 == true) {
    tdown4.start();
    if (set_detik4 == 0 && set_menit4 == 0 && set_jam4 == 0) {
      tdown4.stop();
      sendPhoto = true;
      timer1 = false;
      timer2 = false;
      timer3 = false;
      timer4 = false;
      timer5 = false;
      gerak = false;
      set_detik4 = 0;
      set_menit4 = 10;
      set_jam4 = 0;
      last_set_detik4 = 0;
      last_set_menit4 = 0;
      last_set_jam4 = 0;
    }
  }
  if (timer5 == true) {
    tdown5.start();
    if (set_detik5 == 0 && set_menit5 == 0 && set_jam5 == 0) {
      tdown5.stop();
      sendPhoto = true;
      timer1 = false;
      timer2 = false;
      timer3 = false;
      timer4 = false;
      timer5 = false;
      gerak = false;
      set_detik5 = 30;
      set_menit5 = 12;
      set_jam5 = 0;
      last_set_detik5 = 0;
      last_set_menit5 = 0;
      last_set_jam5 = 0;
    }
  }
  if (gerak == true) {
    Servo1.write(180);
    delay(300);
    Servo1.write(90);
    delay(300);
  }
  if (gerak == false) {
    Servo1.write(90);
  }
}

void print_time1() {
  set_detik1 = set_detik1 - 1;
  if (set_detik1 < 0) {
    set_detik1 = 59;
    set_menit1 = set_menit1 - 1;
  }
  if (set_menit1 < 0) {
    set_menit1 = 59;
    set_jam1 = set_jam1 - 1;
  }
}
void print_time2() {
  set_detik2 = set_detik2 - 1;
  if (set_detik2 < 0) {
    set_detik2 = 59;
    set_menit2 = set_menit2 - 1;
  }
  if (set_menit2 < 0) {
    set_menit2 = 59;
    set_jam2 = set_jam2 - 1;
  }
}
void print_time3() {
  set_detik3 = set_detik3 - 1;
  if (set_detik3 < 0) {
    set_detik3 = 59;
    set_menit3 = set_menit3 - 1;
  }
  if (set_menit3 < 0) {
    set_menit3 = 59;
    set_jam3 = set_jam3 - 1;
  }
}
void print_time4() {
  set_detik4 = set_detik4 - 1;
  if (set_detik4 < 0) {
    set_detik4 = 59;
    set_menit4 = set_menit4 - 1;
  }
  if (set_menit4 < 0) {
    set_menit4 = 59;
    set_jam4 = set_jam4 - 1;
  }
}
void print_time5() {
  set_detik5 = set_detik5 - 1;
  if (set_detik5 < 0) {
    set_detik5 = 59;
    set_menit5 = set_menit5 - 1;
  }
  if (set_menit5 < 0) {
    set_menit5 = 59;
    set_jam5 = set_jam5 - 1;
  }
}
