/*
 * Copyright (c) 2019-2021, Erich Styger
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "Remote.h"
#if PL_CONFIG_USE_REMOTE
#include "McuRTOS.h"
#include "McuUtility.h"
#include "Drive.h"
#include "Shell.h"
#include "Buzzer.h"
#include "McuESP32.h"

/*! \todo ADIS: This is a (mostly empty) template where the remote commands from the ESP32 could be handled. This module should be extended to send data back to the ESP32 */

static QueueHandle_t REMOTE_RxFromESP_Queue;

#define REMOTE_RX_FROM_ESP_QUEUE_LENGTH      32 /* items in queue */
#define REMOTE_RX_FROM_ESP_QUEUE_ITEM_SIZE   1  /* each item is a single character */

/* called by the gateway task to put a char from the ESP into the queue for the remote */
void REMOTE_GatewayRxFromESP(unsigned char ch) {
  if (xQueueSendToBack(REMOTE_RxFromESP_Queue, &ch, pdMS_TO_TICKS(10))!=pdPASS) {
    /* was not possible to put it into the queue: will loose data here */
  }
}

static void RemoteTask(void *pv) {
  unsigned char ch;
  BaseType_t res;

  (void)pv; /* not used */
#if 0 /* example making a beep */
  BUZ_Beep(200, 500);
#endif
#if 0 /* example driving the robot */
  DRV_SetMode(DRV_MODE_SPEED);
  DRV_SetSpeed(500, 500);
  vTaskDelay(pdMS_TO_TICKS(1000));
  DRV_SetMode(DRV_MODE_STOP);
#endif
#if 0 /* example receiving character from queue */
  res = xQueueReceive(REMOTE_RxFromESP_Queue, &ch, pdMS_TO_TICKS(10)); /* wait max 10 ms */
  if (res==errQUEUE_EMPTY) {
    ch = '\0'; /* nothing received */
  }
  res = xQueueReceive(REMOTE_RxFromESP_Queue, &ch, portMAX_DELAY); /* wait 'forever' */
  if (res==errQUEUE_EMPTY) {
    ch = '\0'; /* nothing received */
  }
#endif
  for(;;) {
    res = xQueueReceive(REMOTE_RxFromESP_Queue, &ch, portMAX_DELAY); /* make sure we empty the queue */
    /*! \todo ADIS: implement handling remote stream from ESP **/
  }
}

uint8_t REMOTE_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
  return ERR_OK;
}

void REMOTE_Deinit(void) {
}

void REMOTE_Init(void) {
  if (xTaskCreate(RemoteTask, "Remote", 1024/sizeof(StackType_t), NULL, tskIDLE_PRIORITY+1, NULL) != pdPASS) {
    for(;;){} /* error */
  }
  REMOTE_RxFromESP_Queue = xQueueCreate(REMOTE_RX_FROM_ESP_QUEUE_LENGTH, REMOTE_RX_FROM_ESP_QUEUE_ITEM_SIZE);
  if (REMOTE_RxFromESP_Queue==NULL) {
    for(;;){} /* out of memory? */
  }
  vQueueAddToRegistry(REMOTE_RxFromESP_Queue, "RemoteRxFromESPQueue");
}

#endif /* PL_CONFIG_USE_REMOTE */
