#include <stdlib.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 BUTTON_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 vButtonTask(void* parameters) {
  pinMode(BUTTON_PIN, INPUT);

  while(1) {
    // Serial.println(digitalRead(BUTTON_PIN));
    int output = digitalRead(BUTTON_PIN);
    current = output;

    // My best attempt at printing ONLY when the button has changed state!
    // The last message on the Serial Monitor represents the latest state

    if(current != previous) {
      // Serial.println("Scooper");
      switch (current) {
        case 1:
          Serial.println("Task resumed!");
          break;

        default:
          Serial.println("Task suspended");
          break;
      }
      previous = current;
    } 

    if(output) {
      vTaskResume(xLedHandle);
      // Serial.println("Task resumed!");
    } else {
      vTaskSuspend(xLedHandle);
      // Serial.println("Task suspended!");
    }   
  }
}

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

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

  xTaskCreate(
    vButtonTask,
    "Button Task",
    1024,
    NULL,
    BUTTON_TASK_PRIORITY,
    NULL
  );
  
  vTaskDelete(NULL);
}

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

void loop() {
  
}