// Public Clipboard API.
//
// The formal contract lives in `spec.mbt` (declare-only). This file
// implements the entry points the spec promises.

///|
/// Watch poll interval (ms). Stop is delivered via condition-variable
/// broadcast and is observed within microseconds; this is only the
/// upper bound for how long a quiescent watcher waits before noticing a
/// new clipboard value.
let watch_poll_ms : Int = 500

///|
pub struct Clipboard {
  priv backend : &Backend
}

///|
pub async fn Clipboard::new() -> Clipboard raise ClipboardError {
  { backend: new_for_current_os() }
}

///|
pub fn Clipboard::new_in_memory() -> Clipboard {
  { backend: InMemoryBackend::new() }
}

///|
pub async fn Clipboard::get_text(
  self : Clipboard,
) -> String raise ClipboardError {
  self.backend.get_text()
}

///|
pub async fn Clipboard::set_text(
  self : Clipboard,
  text : String,
) -> Unit raise ClipboardError {
  self.backend.set_text(text)
}

///|
pub async fn Clipboard::watch(
  self : Clipboard,
  group : @async.TaskGroup[Unit],
  on_change : (String) -> Unit,
) -> Handle {
  let h = Handle::new()
  // Seed the baseline so the very first observed value isn't surfaced
  // as a "change". If the seed read fails (e.g. clipboard initially
  // Empty) we tolerate it — the loop will reseed on its first success.
  let mut last : String? = try self.get_text() catch {
    _ => None
  } noraise {
    s => Some(s)
  }
  group.spawn_bg(() => {
    while h.running {
      // Sleep up to `watch_poll_ms` or until `stop()` broadcasts on
      // `h.wakeup`. When stop fires, `with_timeout_opt` returns
      // immediately and the loop exits without an extra poll.
      let _ = @async.with_timeout_opt(watch_poll_ms, () => h.wakeup.wait())
      if !h.running {
        break
      }
      // Tolerate transient read failures (e.g. CLI tool startup race).
      // The next iteration will retry; we just don't surface anything
      // to the caller for this tick.
      try self.get_text() catch {
        _ => ()
      } noraise {
        s =>
          match last {
            Some(prev) if prev == s => ()
            _ => {
              last = Some(s)
              on_change(s)
            }
          }
      }
    }
  })
  h
}