#include <FanStateService.h>

FanStateService::FanStateService(AsyncWebServer* server, FS* fs, SecurityManager* securityManager) :
    _httpEndpoint(FanSettings::read,
                  FanSettings::update,
                  this,
                  server,
                  FAN_SETTINGS_ENDPOINT_PATH,
                  securityManager,
                  AuthenticationPredicates::IS_AUTHENTICATED),
    _fsPersistence(FanSettings::read,
                  FanSettings::update,
                  this,
                  fs,
                  FAN_SETTINGS_FILE) {
                    // pinMode(FAN_PIN, OUTPUT);
                    pinMode(_state.fanPwmGPIO, OUTPUT);
                    // configure settings service update handler to update LED state
                    addUpdateHandler([&](const String& originId) { onConfigUpdated(); }, false);
                  }


void FanStateService::begin() {
  _state.fanStatus = DEFAULT_FAN_STATE;
  Serial.println("Starting The Fan Service + read from FS");
  _fsPersistence.readFromFS();
  onConfigUpdated();
}

void FanStateService::onConfigUpdated() {
  Serial.println(" ** Fan UPDATE (pin " + (String)_state.fanPwmGPIO + ") to " + _state.fanMaxSpeed);
  //digitalWrite(FAN_PIN, _state.fanStatus ? FAN_ON : FAN_OFF);
  analogWrite(_state.fanPwmGPIO, _state.fanMaxSpeed);
}

void FanStateService::save() {
    Serial.println(" ** Fan Write to FS ");
    _fsPersistence.writeToFS();
}