#include <Arduino.h>
#include "soc/soc.h"           // Disable brownour problems
#include "soc/rtc_cntl_reg.h"  // Disable brownour problems
#include "driver/rtc_io.h"
#include <IRremote.h>

int RECV_PIN = 2;

int CountCapture = 0;

unsigned long int runTask;

unsigned long lastWakeupPinHigh = 0;

RTC_DATA_ATTR int bootCount = 0;

#define GPIO_PIN_WAKEUP GPIO_NUM_13
#define EXT_WAKEUP_PIN_BITMASK 0x1000  //  2^12
#define MINIMUM_WAKE_PERIOD_MILLIS 5e3

void gotoSleep(){
  Serial.println("Deep sleep enabled");
  esp_sleep_enable_ext0_wakeup(GPIO_PIN_WAKEUP, LOW);
  esp_deep_sleep_start();
}

void CapturedPhoto(){
  Serial.println("CapturedPhoto");
  CountCapture = CountCapture-1;
}

void setup() {
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  Serial.begin(115200);
  ++bootCount;
  Serial.println("Boot number: " + String(bootCount));
  if(bootCount != 1){
    CountCapture = 5;
  }
  Serial.println();
  Serial.print(F("Sensor Compiled "));
  Serial.println();
  //IrReceiver.begin(RECV_PIN, ENABLE_LED_FEEDBACK); // Start the receiver
  IrReceiver.begin(RECV_PIN, DISABLE_LED_FEEDBACK); // Start the receiver
  Serial.println("IR Receiver ready");
  pinMode(RECV_PIN, INPUT);
  //CountCapture = 5;
}

void loop() {
  unsigned long now=millis();
  Serial.println(CountCapture);
  
  if (IrReceiver.decode()) {
      //Serial.println(IrReceiver.decodedIRData.command);
      // if(now > runTask){
      //   if(CountCapture >= 0){
      //     CountCapture = CountCapture+5;
      //   }
      //   else{
      //     CountCapture = 5;
      //   }
      //   runTask=now+3000;
      // }
      IrReceiver.resume();
  } else {
    if(CountCapture <= 0){
      gotoSleep();
    }
  }
  if(CountCapture >= 1){
    //Serial.println(IrReceiver.decodedIRData.command);
    CapturedPhoto();
  }
  delay(1000);
}