/* ====================================================================
 * Copyright (c) 2009       Martin Hauner
 *                          http://subcommander.tigris.org
 *
 * Subcommander is licensed as described in the file doc/COPYING, which
 * you should have received as part of this distribution.
 * ====================================================================
 */

// sc
#include "ItemFinder.h"
#include "svn/Path.h"

namespace wcview
{

ItemFinder::ItemFinder (const Item* root)
: _root(root)
{
}

Item* ItemFinder::find (const sc::String& name)
{
  if (isDirectChild (name))
    return getDirectChild (name);
  else
    return getNestedChild (name);
}

bool ItemFinder::isDirectChild (const sc::String& name)
{
  sc::String parent = svn::Path::getDirName (name);
  return parent == _root->getName ();
}

Item* ItemFinder::getDirectChild (const sc::String& name)
{
  return _root->getChild (name);
}

Item* ItemFinder::getNestedChild (const sc::String& name)
{
  Item* parent = getDirectChild (getDirectChildDirName (name));
  ItemFinder finder (parent);
  return finder.find (name);
}

sc::String ItemFinder::getDirectChildDirName (const sc::String& name)
{
  QString qPath = QString::fromUtf8(name);
  int idx = qPath.indexOf( '/', _root->getName().getCharCnt()+1 );
  sc::String child = name.left(idx);
  return child;
}

} // namespace
