#include <stdlib.h>
#include <string.h>

// Use only core 1 for demo purposes
#if CONFIG_FREERTOS_UNICORE
static const BaseType_t app_cpu = 0;
#else
static const BaseType_t app_cpu = 1;
#endif

#define LED_TASK_PRIORITY 1
#define SET_STATE_TASK_PRIORITY 2
#define LED_PIN 21
// #define BUTTON_PIN 2
#define BASE_DELAY 500
#define MAX_LENGTH 20

TaskHandle_t xLedHandle = NULL;

bool hasChanged = false;
int previous = 1;
int current = 1;

void vLedTask(void *parameters)
{
  pinMode(LED_PIN, OUTPUT);

  while (1)
  {
    digitalWrite(LED_PIN, HIGH);
    vTaskDelay(BASE_DELAY / portTICK_PERIOD_MS);
    digitalWrite(LED_PIN, LOW);
    vTaskDelay(BASE_DELAY / portTICK_PERIOD_MS);
  }
}

void vSetStateTask(void *parameters)
{
  char c;
  char buf[MAX_LENGTH];
  uint8_t curr = 0;

  // Clear whole buffer
  memset(buf, 0, MAX_LENGTH);

  // Loop forever
  while (1)
  {
    // Read characters from serial
    if (Serial.available() > 0)
    {
      c = Serial.read();
      // Update delay variable and reset buffer if we get a newline character
      if (c == '\n')
      {
        if (!strcmp(strlwr(buf), "suspend"))
        {
          vTaskSuspend(xLedHandle);
        }
        else if (!strcmp(strlwr(buf), "resume"))
        {
          vTaskResume(xLedHandle);
        }

        Serial.print("Update current state to: ");
        Serial.println(buf);

        memset(buf, 0, MAX_LENGTH);
        curr = 0;
      }
      else
      {
        // Only append if index is not over message limit
        if (curr < MAX_LENGTH - 1)
        {
          buf[curr] = c;
          curr++;
        }
      }
    }
  }
}

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

  Serial.println("Please set the current state : ");

  xTaskCreate(
      vLedTask,
      "LED Task",
      1024,
      NULL,
      LED_TASK_PRIORITY,
      &xLedHandle);

  xTaskCreate(
      vSetStateTask,
      "Set State Task",
      1024,
      NULL,
      SET_STATE_TASK_PRIORITY,
      NULL);

  vTaskDelete(NULL);
}

void debugPurposes()
{
  Serial.println(LED_TASK_PRIORITY);
  Serial.println(SET_STATE_TASK_PRIORITY);
}

void loop()
{
}