// The entry of the page: it reads what the server and the browser know about the view,
// and mounts the UI.

///|
/// The kind of the view from the attribute `data-surface` of the page. The server sets
/// it to `desktop` in a window of the desktop app, and to nothing in a browser.
fn surface_of_mark(mark : String) -> @app.Surface {
  match mark {
    "desktop" => Desktop
    _ => Browser
  }
}

///|
/// The instance from the attribute `data-instance` of the page. The server always sets
/// it.
fn instance_of_mark(mark : String) -> @app.InstanceName {
  @app.InstanceName(mark) catch {
    _ => @app.InstanceName::of_channel(Stable)
  }
}

///|
/// The connection of the page. `origin` is the origin of the server, for example
/// `http://127.0.0.1:3090`. A text that is not a view key is as no key: only a new page
/// from the server helps.
fn page_connection(origin : String, key : String) -> Connection {
  let key = ViewKey::ViewKey(key) catch {
    _ => return Connection::without_key()
  }
  Connection::to_hub("\{origin}/hub", key, () => {
    check_session("\{origin}/session", key)
  })
}

///|
extern "js" fn page_origin() -> String =
  #| () => location.origin

///|
/// The attribute `data-surface` of the page, or an empty text.
extern "js" fn surface_mark() -> String =
  #| () => document.documentElement.dataset.surface ?? ""

///|
/// The attribute `data-instance` of the page, or an empty text.
extern "js" fn instance_mark() -> String =
  #| () => document.documentElement.dataset.instance ?? ""

///|
/// The computer has macOS, or a system of Apple with the same shortcuts.
extern "js" fn is_mac() -> Bool =
  #| () => /^(Mac|iP)/.test(navigator.platform)

///|
fn main {
  // The first page of the server kept the view key.
  let key = stored_text("mission-control-view-key")
  let connection = page_connection(page_origin(), key)
  let surface = surface_of_mark(surface_mark())
  let instance = instance_of_mark(instance_mark())
  let primary_sidebar = PrimarySidebar::of_stored(
    stored_text(primary_sidebar_key),
  )
  @rabbita.new(() => {
    app(connection, surface~, instance~, primary_sidebar~, mac=is_mac())
  }).mount("app")
}