/**
 * @file app.ino
 * @author Anatole SCHRAMM-HENRY
 * @brief SAB App entry point.
 * @date 24/02/2019
 * 
 * @copyright MIT
 * 
 */
#include "definition.h" 
#include "SAB.h"
#include "views.h"
#include "webApi.h"
#include "tasks.h"
#include "CFGDictionary.h"
#include "CFGParameterValue.h"
#include "EventHandler.h"
#include "NonBlockingDelay.h"
#define DEBUG

SAB sab;
EventHandler evHan;
EventHandler::Event evt;

NonBlockingDelay dataRefreshNBD(1000);

volatile boolean ioStateChange(false);
View1Packet v1p = {sab.getRtcManager().getDateTime(), sab.getSdCardManager().getSize(GBYTE), sab.getPowerManager().getPowerInfo(),0, sab.getSoftVersion(), &sab};
ViewAPPacket vap = {sab.getConnectivityManager().softAPmacAddress(), sab.getConnectivityManager().softAPSSID(), sab.getConnectivityManager().softAPIP(), sab.getConnectivityManager().softAPgetStationNum(), sab.getConnectivityManager().isAPEnabled()};
ViewSTAPacket vstap = {sab.getConnectivityManager().macAddress(), sab.getConnectivityManager().localIP(), sab.getConnectivityManager().RSSI(), sab.getConnectivityManager().isSTAEnabled()};
ViewIoInfoPacket vio = {{0},{0}};
SdCardApiPacket sdCardApiPacket = {NULL, NULL};

//DataLogger dataLogger = {HttpClient("192.168.0.17", "/esp8266/dataLogger.php", 1234), 0, false};

void setup() 
{
  // put your setup code here, to run once:
  Serial.println("Starting setup");
  CFGFileParser cfgFileParser(sab.getSdCardManager(), AP_CFG_FILE);
  CFGDictionary<CFGParameterValue> *cfgDictionary = (CFGDictionary<CFGParameterValue> *) cfgFileParser.parseFile();
  
  if(cfgDictionary != NULL)
  {
    Serial.printf("AP PASSWORD : %s\n",
    (*cfgDictionary)("PASSWORD") ? (*cfgDictionary)("PASSWORD")->stringValue() : "");
  }

  #if 0
  CFGFileParser cfgFileParsert1(sab.getSdCardManager(), "/CONFIG/TEST1.CFG");
  CFGFileParser cfgFileParsert2(sab.getSdCardManager(), "/CONFIG/TEST2.CFG");
  
  Serial.print("TEST1 : ");Serial.println(cfgFileParsert1.save(cfgDictionary));
  Serial.print("TEST2 : ");Serial.println(cfgFileParsert2.save(cfgDictionary));
  #endif
  
  delete cfgDictionary;
  
  sab.getScreenManager().addView(&(homeInfo), &v1p, 0);
  sab.getScreenManager().addView(&(rtcInfo), &sab, 1);
  sab.getScreenManager().addView(&(apInfo), &vap, 2);
  sab.getScreenManager().addView(&(staInfo), &vstap, 3);
  sab.getScreenManager().addView(&(memInfo), NULL, 4);
  sab.getScreenManager().addView(&(ioInfo), &vio, 5);
  sab.getScreenManager().addView(&(sysErrorInfo), &sab, 6);
  sab.getScreenManager().addView(NULL, NULL, 7); //for testing purposes
  sab.getScreenManager().addView(&(dummy), NULL, 8); //for testing purposes

  sab.getScreenManager().displayView(0);
  if(sab.getRTC_DS3231().lostPower())
  {
    Serial.println("Clock lost power");
    sab.getRTC_DS3231().adjust(DateTime(F(__DATE__), F(__TIME__)));
    sab.getRtcManager().setDateTime(sab.getRTC_DS3231().now());
  }
  
  sab.getWebServerManager().getWEBServer().addHttpHeader("Access-Control-Allow-Origin", "*");

  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/web/apitester", &(apiTesterApi), NULL);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/view/next", &(nextViewApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/view/reloadcfg", &(reloadViewApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/view", &(viewByUIDApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/rtc/get/datetime", &(rtcGetTimeApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/rtc/set/datetime", &(rtcSetTimeApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/sdcard/size", &(sdCardSizeApi), &sab, WEBServer<WEBClient>::GET);
  sdCardApiPacket.pSab = &sab;sdCardApiPacket.pView = &v1p;
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/sdcard/action", &(sdCardActionApi), &sdCardApiPacket, WEBServer<WEBClient>::GET);
  
  sab.getWebServerManager().getWEBServer().addApiRoutine("/esp/restart", &(espRestartApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/esp/reset", &(espResetApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/wifi/stainfo", &(staWifiInfoApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/wifi/apinfo", &(apWifiInfoApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/wifi/scanner", &(apScannerApi), NULL, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/systeminfo", &(systemInfoApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/power/info", &(powerInfoApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/io/get/level", &(ioGetLevelApi), vio.ioState, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/io/set/level", &(ioSetLevelApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/io/get/mode", &(ioGetModeApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/io/set/mode", &(ioSetModeApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/ota/update/upload", &(otaUpdateUploadApi), NULL, WEBServer<WEBClient>::POST);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/ota/update/device", &(otaUpdateRemoteApi), &sab, WEBServer<WEBClient>::GET);
  sab.getWebServerManager().getWEBServer().addApiRoutine("/sab/web/cookietest", &(cookieTestApi), &sab, WEBServer<WEBClient>::GET);

  sab.getIOManager().setISROnIOChange(&(ioISR), GPIO_3_RX);

  sab.getTaskSchedulerManager().addTask((uint16_t)0, TaskSchedulerManagerHelper::Schedule::scheduleBuilder()->setMillis(5000), &(task_blink), &sab);
  sab.getTaskSchedulerManager().addTask(1, TaskSchedulerManagerHelper::Schedule::scheduleBuilder()->setSeconds(10), &(task_sys_info), &v1p);
  sab.getTaskSchedulerManager().addTask(2, TaskSchedulerManagerHelper::Schedule::scheduleBuilder()->setSeconds(5), &(testTask), &sab);
  //dataLogger.client.keepAlive(true);
  //sab.getTaskSchedulerManager().addTask(2, TaskSchedulerManagerHelper::Schedule::scheduleBuilder()->setSeconds(1)->setTriggerRightAway(false), &(task_post_data_logger), &dataLogger);

  Serial.println("End setup");
}

void loop() 
{
  
  if(dataRefreshNBD || ioStateChange)
  {
    v1p.dateTime = sab.getRtcManager().getDateTime();
    v1p.nbViews = sab.getScreenManager().getViewCount();
    vap.ipAddr = sab.getConnectivityManager().softAPIP();
    vap.macAddr = sab.getConnectivityManager().softAPmacAddress();
    vap.nbOfCon = sab.getConnectivityManager().softAPgetStationNum();
    vstap.macAddr = sab.getConnectivityManager().macAddress();
    vstap.ipAddr = sab.getConnectivityManager().localIP();
    vstap.sigStrength = sab.getConnectivityManager().RSSI();

    sab.getIOManager().getPcf().digitalReadAll(vio.ioState);
    sab.getIOManager().getPcf().getPinModeAll(vio.ioMode);

    if(ioStateChange)
    {
      sab.getScreenManager().forceRefresh();
      Serial.println(F("ISR triggered"));
      ioStateChange = false;
    }
  }
  
  evt = evHan.getEvent();
  switch(evt)
  {
    case EventHandler::Event::FLASH_BUTTON_PRESS:
      sab.getScreenManager().displayNextView();
      #ifdef DEBUG
      Serial.printf("Changing view\nSelected view is : %d\n",sab.getScreenManager().getCurrentViewUID());
      #endif
      break;
    case EventHandler::Event::FLASH_BUTTON_LONG_PRESS:
      sab.getScreenManager().displayPreviousView();
      #ifdef DEBUG
      Serial.printf("Changing view\nSelected view is : %d\n",sab.getScreenManager().getCurrentViewUID());
      #endif
      break;
    default: //NO_EVENT
      break;
  }
  
  //Run the different services
  sab.run();
  evHan.run();
}

IRAM_ATTR void ioISR()
{
  ioStateChange = true;
}
