#include <Arduino.h>
#include <ArduinoJson.h>
const int IR_SEND_PIN = 12;
const int IR_RECEIVE_PIN = 14;
const int CONTROL_LED_PIN = 13;
#include <IRremote.hpp>
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void handleIncomingSerialBTData(void *pvParameters);
void handleIncomingIRSignals(void *pvParameters);

void sendDataBT(String data);

void setup()
{
  Serial.begin(115200); // Start the serial communication
  SerialBT.begin("ESP32");
  pinMode(CONTROL_LED_PIN, OUTPUT);                       // Set LED pin as output
  pinMode(IR_SEND_PIN, OUTPUT);                           // Set IR LED pin as output
  IrReceiver.begin(IR_RECEIVE_PIN, DISABLE_LED_FEEDBACK); // Initialize the IR receiver
  IrSender.begin(IR_SEND_PIN);                            // Initialize the IR sender
  Serial.println("IR Receiver Ready!");

  xTaskCreate(handleIncomingSerialBTData, "handleIncomingSerialBTData", 2048, NULL, 1, NULL);
  xTaskCreate(handleIncomingIRSignals, "handleIncomingIRSignals", 2048, NULL, 1, NULL);
}

void loop()
{
  delay(200);
}

void handleIncomingIRSignals(void *pvParameters)
{
  while (true)
  {
    if (IrReceiver.decode())
    {
      IRData data;
      data = IrReceiver.decodedIRData;
      IrReceiver.printIRResultShort(&Serial, &data, false);
      digitalWrite(CONTROL_LED_PIN, HIGH);
      delay(200);
      digitalWrite(CONTROL_LED_PIN, LOW);
      IrReceiver.resume();
    }
  }
}

void handleIncomingSerialBTData(void *pvParameters)
{
  while (true)
  {
    String data = "";
    while (SerialBT.available())
    {
      char c = SerialBT.read();
      data.concat(c);
    }
    if (data != "")
    {
      Serial.println(data);

      JsonDocument doc;
      deserializeJson(doc, data);
      String protocol = doc["protocol"];
      int address = doc["address"];
      int command = doc["command"];

      digitalWrite(CONTROL_LED_PIN, HIGH);
      if (protocol == "samsung") {

          IrSender.sendSamsung(address, command, 4);
      }
      digitalWrite(CONTROL_LED_PIN, LOW);
    }
    delay(25);
  }
}

void sendDataBT(String data)
{
  uint8_t buf[data.length()];
  memcpy(buf, data.c_str(), data.length());
  SerialBT.write(buf, data.length());
  SerialBT.println();
}