#include <qthing>

#include "esp_log.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"


#include "CyanLight.hpp"
#include "SiliconTorch/FxCyanF.hpp"

#include <SpiderLib.hpp>


#include "SiliconTorch/NVSExplorer.hpp"



#include "SiliconTorch/Service/FxCyanF.hpp"
#include "SiliconTorch/Service/Service.hpp"
#include "SiliconTorch/Service/ServiceManager.hpp"




CyanLight::CyanLightControl* ctrl = NULL;



SiliconTorch::ServiceManager::Service* fxCyan = NULL;
SiliconTorch::ServiceManager::ServiceManager* mgr = NULL;



void device_main() {


  qthing::Config cfg;

  // Needed for packet parsing, animation rendering and stuff
  qthing::power_managment_max_power();






  SemaphoreHandle_t mutex000 = xSemaphoreCreateBinary();

  // Do it in another task do control stack size
  new SpiderLib::Util::LambdaTask([&]() {
    // Trigger singleton initialization
    SiliconTorch::NVSExplorer::NVSExplorer::instance();


    mgr = new SiliconTorch::ServiceManager::ServiceManager();



    // fxCyan = new SiliconTorch::Service::FxCyanF();

    // fxCyan->start();


    xSemaphoreGive(mutex000);
  });

  xSemaphoreTake(mutex000, portMAX_DELAY);  // avoid races with MQTT subscriptions (TODO: do we lock with WLAN atm???)

  qthing::enable_wifi();
  return;








  SemaphoreHandle_t mutex = xSemaphoreCreateBinary();

  // Do it in another task do control stack size
  new SpiderLib::Util::LambdaTask([&]() {
    // Trigger singleton initialization
    SiliconTorch::NVSExplorer::NVSExplorer::instance();

    SiliconTorch::FxCyanF::configureFromNVS();

    xSemaphoreGive(mutex);
  });

  xSemaphoreTake(mutex, portMAX_DELAY);  // avoid races with MQTT subscriptions (TODO: do we lock with WLAN atm???)

  qthing::enable_wifi();
  return;




  // #############################
  // ### CLC-Drucker init code ###
  // #############################


/*
  ctrl = new CyanLight::CyanLightControl(3);
  
  ctrl->setFrqRes(100, 19);


  for (u8 i = 0; i < 100; i++) {

    bool _f = i % 2 == 0;

    ctrl->setPWM(0,  _f      * 1.0f);
    ctrl->setPWM(2, (_f ^ 1) * 1.0f);

    vTaskDelay(50 / portTICK_PERIOD_MS);
  }


  ctrl->setPWM(0, 0.0f);
  ctrl->setPWM(1, 0.0f);
  ctrl->setPWM(2, 1.0f);


  qthing::enable_wifi();
  cfg.apply();

  return;
*/


  // ### end CLC-Drucker ###
  // #############################






  auto delay = 10 / portTICK_PERIOD_MS;
  float limit = 50.0f;

  while (true) {
    for (u8 i = 0; i < limit; i++) {
      float pwm = i / limit;
      ctrl->setPWM(0, pwm*pwm);
      vTaskDelay(delay);
    }

    for (u8 i = 0; i < limit; i++) {
      float pwm = i / limit;
      ctrl->setPWM(0, 1.0f - pwm*pwm);
      vTaskDelay(delay);
    }
  }
}