#include <Arduino.h>
const int IR_SEND_PIN = 12;    // GPIO12 for the IR LED
#include <IRremote.hpp>
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

const int ReceiverPin = 14; // GPIO14 for the IR receiver (TSOP48)
const int LedPin = 13;      // GPIO13 for the external LED

IRData data;


// put function declarations here:
int myFunction(int, int);
void parallelLoop(void *pvParameters);
void handleSerialBT(void *pvParameters);

void setup()
{
  Serial.begin(115200);                                // Start the serial communication
  SerialBT.begin("ESP32");
  pinMode(LedPin, OUTPUT);                             // Set LED pin as output
  pinMode(IR_SEND_PIN, OUTPUT);                           // Set IR LED pin as output
  IrReceiver.begin(ReceiverPin, DISABLE_LED_FEEDBACK); // Initialize the IR receiver
  Serial.println("IR Receiver Ready!");
  xTaskCreate(parallelLoop, "parallelLoop", 2048, NULL, 1, NULL); // Create a task for parallel loop
  xTaskCreate(handleSerialBT, "handleSerialBT", 2048, NULL, 1, NULL); // Create a task for serial BT communication
}

void loop()
{
  if (IrReceiver.decode())
  {                                         // Check if IR signal is received
    IrReceiver.printIRResultShort(&Serial); // Print IR signal details to Serial Monitor
    data = IrReceiver.decodedIRData;
    digitalWrite(LedPin, HIGH);             // Turn on the LED
    delay(200);                             // Keep LED on for 200ms
    digitalWrite(LedPin, LOW);              // Turn off the LED
    IrReceiver.resume();                    // Prepare to receive the next IR signal
  }
}

void parallelLoop(void *pvParameters)
{
  while (true)
  {
    delay(5000);
    digitalWrite(IR_SEND_PIN, HIGH);
    delay(5000);
    digitalWrite(IR_SEND_PIN, LOW);
  }
}

void handleSerialBT(void *pvParameters)
{
  while (true)
  {
    if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(25);
  }
}

// put function definitions here:
int myFunction(int x, int y)
{
  return x + y;
}