///|
priv struct LocatedShot {
  clip : Int32
  timeline : Span
  media : String?
  source : Span?
}

///|
pub struct Timeline {
  priv shots : Array[LocatedShot]
  priv length_frames : Int64
}

///|
pub fn Timeline::from_shots(
  shots : Array[Shot],
) -> Timeline raise ReconformError {
  if shots.length() > 20000 {
    raise Limit("too many shots; limit is 20000")
  }
  let located = []
  let mut cursor = 0L
  for i, shot in shots {
    let (media, source, length) = match shot {
      Clip(id, source) => {
        if id.length() == 0 {
          raise Invalid("clip media key is empty")
        }
        source.checked("source span")
        (Some(id), Some(source), source.length())
      }
      Gap(n) => {
        if n <= 0L {
          raise Invalid("gap must have positive duration")
        }
        (None, None, n)
      }
    }
    let stop = add_frames(cursor, length)
    located.push({ clip: i, timeline: { start: cursor, stop, }, media, source, })
    cursor = stop
  }
  { shots: located, length_frames: cursor, }
}

///|
pub fn Timeline::duration(self : Timeline) -> Int64 {
  self.length_frames
}

///|
pub fn Timeline::shot_count(self : Timeline) -> Int32 {
  self.shots.length()
}

///|
fn Timeline::first_shot(self : Timeline, start : Int64) -> Int32 {
  let mut lo = 0
  let mut hi = self.shots.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    if self.shots[mid].timeline.stop <= start {
      lo = mid + 1
    } else {
      hi = mid
    }
  }
  lo
}

///|
fn intersection(a : Span, b : Span) -> Span? {
  let start = if a.start > b.start { a.start } else { b.start }
  let stop = if a.stop < b.stop { a.stop } else { b.stop }
  if start < stop {
    Some({ start, stop, })
  } else {
    None
  }
}