// Copyright thibaut

// History:
//   13 Jun 12  thibaut Creation

using flux

** Standard Fantom NavBar is "internal" so using dynamic calls tricks to work with it
const class NavBarHelper
{
  static const NavBarHelper cur := make

  private new make() {}

  ** Refresh a NavBar Node
  Void refreshNode(Frame frame, File f)
  {
    nb := getNavBar(frame)
    node := findNode(nb, f.uri)
    if(node!=null)
      nb->onRefresh(node)
  }

  ** Select a NavBar Node
  ** TODO: Not working, dunno why
  Void selectNode(Frame frame, File f)
  {
    nb := getNavBar(frame)
    node := findNode(nb, f.uri)
    if(node!=null)
    {
      nb->active->select(node)
    }
  }

  ** Retrieve the NavBar sidebar
  SideBar? getNavBar(Frame frame)
  {
    // Note, it's the sidebar but we can't use NabBar directly as it's marked internal
    frame.sideBars.find {it.typeof.qname == "flux::NavBar"}
  }

  ** Recursively find a NavNode (by uri) in the NavBar tree
  ** Not super efficient but OK
  Obj? findNode(SideBar navBar, Uri nodeUri, Obj? node := null)
  {
    nodes := node == null ? navBar->active->model->roots : navBar->active->model->children(node)
    Obj? found := nodes->eachWhile |Obj n->Obj?|
    {
      uri := n->uri as Uri
      if(uri == nodeUri)
      {
        return n
      }
      if(nodeUri.toStr.startsWith(uri.toStr))
      {
       return findNode(navBar, nodeUri, n)
      }
      return null
    }
    return found
  }


}