/* ====================================================================
 * Copyright (c) 2007-2008  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 "Compare.h"
#include "String.h"
#include "svn/Path.h" // \todo circular dependency between util <-> svn

// sys
#include <cstring>


int calcDepth( const sc::String& s )
{
  int depth = 0;
  const char* c = (const char*)s;
  for( sc::Size cnt = 0; cnt < s.getByteCnt(); cnt++ )
  {
    if( c[cnt] == '/' )
      depth++;
  }
  return depth;
}


int compare3( const sc::String& a, bool adir, const sc::String& b, bool bdir )
{
  if( ! adir && ! bdir )
  {
    sc::String ap = svn::Path::getDirName(a);
    sc::String bp = svn::Path::getDirName(b);

    if( ap == bp )
    {
      sc::String ab = svn::Path::getBaseName(a);
      sc::String bb = svn::Path::getBaseName(b);
      return compare3(ab,bb);
    }

    if( ap.getByteCnt() <= bp.getByteCnt() )
    {
      int r = strncmp( ap, b, ap.getByteCnt() );
      if( r != 0 )
        return r < 0 ? -1 : 1;

      return 1;
    }
    else
    {
      int r = strncmp( a, bp, bp.getByteCnt() );
      if( r != 0 )
        return r < 0 ? -1 : 1;

      return -1;
    }
  }

  if( adir && !bdir )
  {
    sc::String bp = svn::Path::getDirName(b);

    if( a.getByteCnt() <= bp.getByteCnt() )
    {
      int r = strncmp( a, bp, a.getByteCnt() );
      if( r != 0 )
        return r < 0 ? -1 : 1;

      return -1;
    }
    else
    {
      int r = strncmp( a, bp, bp.getByteCnt() );
      if( r != 0 )
        return r < 0 ? -1 : 1;

      return -1;
    }
  }

  if( !adir && bdir )
  {
    sc::String ap = svn::Path::getDirName(a);

    if( ap.getByteCnt() <= b.getByteCnt() )
    {
      int r = strncmp( ap, b, ap.getByteCnt() );
      if( r != 0 )
        return r < 0 ? -1 : 1;

      return 1;
    }
    else
    {
      int r = strncmp( ap, b, b.getByteCnt() );
      if( r != 0 )
        return r < 0 ? -1 : 1;

      return 1;
    }
  }

  int result = compare3(a,b);
  return result;
}
