// 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),
  )
  let sidebar_width = SidebarWidth::of_stored(stored_text(sidebar_width_key))
  let secondary_sidebar = SecondarySidebar::of_stored(
    stored_text(secondary_sidebar_key),
  )
  let secondary_sidebar_width = SecondarySidebarWidth::of_stored(
    stored_text(secondary_sidebar_width_key),
  )
  let companion_panel = CompanionPanel::of_stored(
    stored_text(companion_panel_key),
  )
  let color_scheme = ColorScheme::of_stored(stored_text(color_scheme_key))
  let appearance = Appearance::of_stored(stored_text(appearance_key))
  let brand = BrandConfig::of_stored(stored_text(brand_key))
  @rabbita.new(() => {
    app(
      connection,
      surface~,
      instance~,
      primary_sidebar~,
      sidebar_width~,
      secondary_sidebar~,
      secondary_sidebar_width~,
      companion_panel~,
      mac=is_mac(),
      color_scheme~,
      appearance~,
      brand~,
    )
  }).mount("app")
}