///|
/// An explicit reactive session. It owns the current inputs and the last
/// successful view. Each update replaces inputs atomically and recomputes the
/// full projection; a failed update keeps both the inputs and the view.
pub struct Session[A, V] {
  priv mut model : Model
  priv mut state : A
  priv mut view_state : V
  priv mut policies : ReadOnlyArray[Policy[A, V]]
  priv mut current : View
  priv mut revision : Int32
  priv mut error : ProjectionError?
}

///|
pub fn[A, V] Session::new(
  model : Model,
  state : A,
  view : V,
  policies~ : ArrayView[Policy[A, V]] = [],
) -> Result[Session[A, V], ProjectionError] {
  match project(model, state, view, policies~, revision=1) {
    Ok(current) =>
      Ok({
        model,
        state,
        view_state: view,
        policies: ReadOnlyArray::from_array(policies),
        current,
        revision: 1,
        error: None,
      })
    Err(error) => Err(error)
  }
}

///|
/// The last successful view.
pub fn[A, V] Session::view(self : Session[A, V]) -> View {
  self.current
}

///|
/// The input revision of the last successful view. It starts at 1 and grows
/// by one for each successful update.
pub fn[A, V] Session::revision(self : Session[A, V]) -> Int32 {
  self.revision
}

///|
/// The error of the last update, if it failed.
pub fn[A, V] Session::error(self : Session[A, V]) -> ProjectionError? {
  self.error
}

///|
pub fn[A, V] Session::model(self : Session[A, V]) -> Model {
  self.model
}

///|
pub fn[A, V] Session::state(self : Session[A, V]) -> A {
  self.state
}

///|
pub fn[A, V] Session::view_state(self : Session[A, V]) -> V {
  self.view_state
}

///|
/// Replace any inputs at once. Absent inputs keep their current value. A new
/// model revision needs view state whose handles come from that revision; an
/// override that names an older revision fails with `RevisionMismatch`.
pub fn[A, V] Session::update(
  self : Session[A, V],
  model? : Model,
  state? : A,
  view? : V,
  policies? : ArrayView[Policy[A, V]],
) -> Result[View, ProjectionError] {
  let next_model = model.unwrap_or(self.model)
  let next_state = state.unwrap_or(self.state)
  let next_view = view.unwrap_or(self.view_state)
  let next_policies = match policies {
    Some(values) => ReadOnlyArray::from_array(values)
    None => self.policies
  }
  match
    project(
      next_model,
      next_state,
      next_view,
      policies=next_policies[:],
      revision=self.revision + 1,
    ) {
    Ok(current) => {
      self.model = next_model
      self.state = next_state
      self.view_state = next_view
      self.policies = next_policies
      self.current = current
      self.revision += 1
      self.error = None
      Ok(current)
    }
    Err(error) => {
      self.error = Some(error)
      Err(error)
    }
  }
}