//
// IMPORTANT:
//  before flashing this the first time,
//  upload the "prepareFilesystem.ino" example sketch from ESPUI
//  without that critical files are missing
//
//  This was done to reduce the PROGMEM footprint of this program
//

#include <Arduino.h>
#include <WiFi.h>
#include <WiFiManager.h>

#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ESPUI.h>

#include "Config.h"
#include "Core.h"
#include "UI.h"

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  delay(300);

  Serial.println("Booting Analog System Monitor (UDP + LEDC + WiFiManager + Slew)");
  Serial.print("Firmware: ");
  Serial.println(FIRMWARE_VERSION);

  // WiFi Manager
  WiFiManager wm;
  wm.setHostname("AnalogMonitor");
  wm.setTimeout(180);

  Serial.println("Starting WiFiManager...");
  bool res = wm.autoConnect("AnalogMonitor-Setup");

  if (!res) {
    Serial.println("WiFi failed or timed out. Rebooting...");
    delay(2000);
    ESP.restart();
  }

  Serial.println("WiFi connected!");
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());

  // Core init (PWM, prefs, UDP, calibration, state)
  coreInit();

  // ESPUI Web Interface
  ESPUI.setVerbosity(Verbosity::Verbose);

  uint16_t tabSettings, tabLighting, tabCalibration;
  uiInit(tabSettings, tabLighting, tabCalibration);

  ESPUI.sliderContinuous = true;   // enables live slider updates
  ESPUI.beginLITTLEFS("Analog System Monitor UI");
}

void loop() {
  coreHandleUDP();
  coreUpdateState();
}
