#include "torlinkc/ui/clock.hpp"

#include <cmath>

#include <ftxui/component/animation.hpp>
#include <ftxui/component/component_base.hpp>
#include <ftxui/dom/elements.hpp>

namespace torlinkc::ui {

namespace {

// Large relative to any consumer's period, so wrapping here never produces
// a visible seam in their own fmod()-based math.
constexpr float kWrap = 100000.0f;

class UiClockComponent : public ftxui::ComponentBase {
 public:
  UiClockComponent(float* clock, std::function<bool()> isActive) : clock_(clock), isActive_(std::move(isActive)) {}

  ftxui::Element Render() override { return ftxui::text(""); }

  void OnAnimation(ftxui::animation::Params& params) override {
    if (!isActive_()) return;
    *clock_ = std::fmod(*clock_ + params.duration().count(), kWrap);
    ftxui::animation::RequestAnimationFrame();
  }

 private:
  float* clock_;
  std::function<bool()> isActive_;
};

}  // namespace

ftxui::Component MakeUiClock(float* clock, std::function<bool()> isActive) {
  return ftxui::Make<UiClockComponent>(clock, std::move(isActive));
}

}  // namespace torlinkc::ui
