#include <FanStateService.h>





FanStateService::FanStateService(AsyncWebServer* server, FS* fs, SecurityManager* securityManager, AsyncMqttClient* mqttClient, FanMqttSettingsService* fanMQTTSettingsService) :
    _httpEndpoint(FanState::read,
                  FanState::update,
                  this,
                  server,
                  FAN_SETTINGS_ENDPOINT_PATH,
                  securityManager,
                  AuthenticationPredicates::IS_AUTHENTICATED),
    _mqttPubSub(FanState::haRead, FanState::haUpdate, this, mqttClient),
    _fsPersistence(FanState::read,
                  FanState::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();

  this->oneWire1.begin(_state.OneWireGPIO);
  this->sensor_intake.setOneWire(&this->oneWire1);
  this->sensor_intake.begin();

  // attachInterrupt(_state.fanTachGPIO,handleInterrupt,RISING);

  onConfigUpdated();
  lastpoll = millis();
}

void FanStateService::SetLastPoll(unsigned long l) {
  this->lastpoll = l;

}

int FanStateService::getTachGPIO() {
  return _state.fanTachGPIO;
}

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();
}

void FanStateService::compute() {
  unsigned long period = millis() - this->lastpoll;
  this->sensor_intake.requestTemperatures();
  this->Tin  = this->sensor_intake.getTempCByIndex(0);
  this->Tout = this->sensor_intake.getTempCByIndex(1);
  float curRpm = 60000/period*this->RPM/2;  // Hall sensor = 2 tick per rotation
  Serial.print("Intake: " + (String) this->Tin + " - " + (String) this->Tout + " [ "+ (String) curRpm + " RPM ]\n");
  this->RPM=0;
}