#include "speed_fan.h"
#include "esphome/core/log.h"

namespace esphome::speed {

static const char *const TAG = "speed.fan";

void SpeedFan::setup() {
  // Construct traits before restore so preset modes can be looked up by index
  this->traits_ = fan::FanTraits(this->oscillating_ != nullptr, true, this->direction_ != nullptr, this->speed_count_);

  auto restore = this->restore_state_();
  if (restore.has_value()) {
    restore->apply(*this);
    this->write_state_();
  }
}

void SpeedFan::dump_config() { LOG_FAN("", "Speed Fan", this); }

void SpeedFan::control(const fan::FanCall &call) {
  auto call_state = call.get_state();
  if (call_state.has_value())
    this->state = *call_state;
  auto call_speed = call.get_speed();
  if (call_speed.has_value())
    this->speed = *call_speed;
  auto call_oscillating = call.get_oscillating();
  if (call_oscillating.has_value())
    this->oscillating = *call_oscillating;
  auto call_direction = call.get_direction();
  if (call_direction.has_value())
    this->direction = *call_direction;
  this->apply_preset_mode_(call);

  this->write_state_();
  this->publish_state();
}

void SpeedFan::write_state_() {
  float speed = this->state ? static_cast<float>(this->speed) / static_cast<float>(this->speed_count_) : 0.0f;
  this->output_->set_level(speed);
  if (this->oscillating_ != nullptr)
    this->oscillating_->set_state(this->oscillating);
  if (this->direction_ != nullptr)
    this->direction_->set_state(this->direction == fan::FanDirection::REVERSE);
}

}  // namespace esphome::speed
