#pragma once

#include <cstdint>

#include "core/preview_clock.hpp"

namespace smartcut::core {

enum class SyncAction { present, hold_video, advance_video };

class PreviewSynchronizer {
 public:
  PreviewSynchronizer(RationalTimebase audio_timebase, RationalTimebase video_timebase, std::int64_t tolerance_ticks)
      : clock_(audio_timebase, video_timebase), tolerance_ticks_(tolerance_ticks) {}
  SyncAction update(std::int64_t audio_pts, std::int64_t video_pts) {
    clock_.set_audio_pts(audio_pts); clock_.set_video_pts(video_pts);
    const auto drift = clock_.video_drift_ticks();
    if (drift > tolerance_ticks_) return SyncAction::hold_video;
    if (drift < -tolerance_ticks_) return SyncAction::advance_video;
    return SyncAction::present;
  }
  std::int64_t drift_ticks() const { return clock_.video_drift_ticks(); }
 private:
  PreviewClock clock_;
  std::int64_t tolerance_ticks_;
};

}  // namespace smartcut::core
