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

#include "platform.h"
#if PL_CONFIG_USE_UNIT_TESTS
#include "tests.h"
#include "unity.h"
#include "McuUnity.h"
#include "McuRTOS.h"
#include "McuShell.h"
#include "McuRTT.h"
#include "McuUtility.h"
#include "McuLog.h"
#include "test_sensors.h"
#include "test_dns_resolver.h"
#include "test_mqtt_client.h"


static void TestArgFailed(void) {
  TEST_ASSERT_MESSAGE(false, "wrong test_arg value");
}

static void TestDummy(void) {
  TEST_ASSERT_TRUE_MESSAGE(true, "Dummy test always passes");
}


void Tests_Run(void) {
  int nofFailures;
  uint32_t test_arg = -1;
  int nofBytes;
  unsigned char buf[32];

  nofBytes = McuUnity_RTT_GetArgs(buf, sizeof(buf));
  UNITY_BEGIN();
  if (nofBytes>0) {
    if (McuUtility_strcmp(buf, "dummy")==0) {
      RUN_TEST(TestDummy);
    } else if (McuUtility_strcmp(buf, "sensors")==0) {
      RUN_TEST(TestSensors_Test);
    } else if (McuUtility_strcmp(buf, "dns")==0) {
      RUN_TEST(TestDnsResolver_Test);
    }
    else if (McuUtility_strcmp(buf, "mqtt")==0) {
      RUN_TEST(test_MqttClient_Init_SetsDefaults);
      RUN_TEST(test_MqttClient_SetDoPublish_On);
      RUN_TEST(test_MqttClient_SetDoPublish_Off);
      RUN_TEST(test_MqttClient_Publish_Disabled);
    }
    else {
      RUN_TEST(TestArgFailed);
    }
  } else {
    RUN_TEST(TestArgFailed);
  }
  nofFailures = UNITY_END();
#if PL_CONFIG_USE_RTT
  McuUnity_Exit_JRun_RTT(nofFailures==0);
#else
  McuUnity_Exit_LinkServer_Log(nofFailures==0);
#endif
}

static void TestTask(void *pv) {
  McuLog_info("starting test task");
  vTaskDelay(pdMS_TO_TICKS(100)); /* give sensor some time */
  Tests_Run();
  vTaskDelete(NULL); /* terminate task */
}

void Tests_Init(void) {
  if (xTaskCreate(
      TestTask,  /* pointer to the task */
      "Test", /* task name for kernel awareness debugging */
      1500/sizeof(StackType_t), /* task stack size */
      (void*)NULL, /* optional task startup argument */
      tskIDLE_PRIORITY,  /* initial priority */
      (TaskHandle_t*)NULL /* optional task handle to create */
    ) != pdPASS)
  {
    McuLog_fatal("Failed creating task");
    for(;;){} /* error! probably out of memory */
  }
}
#endif /* PL_CONFIG_USE_UNIT_TESTS */