/* ====================================================================
 * Copyright (c) 2007,      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 "ProjectSorter.h"
#include "Project.h"


class sortProject
{
public:
  sortProject() {}

  bool operator()( Project* lh, Project* rh )
  {
    return lh->getSortPos() < rh->getSortPos();
  }
};


ProjectSorter::ProjectSorter( const Projects& projects ) : _projects(projects)
{
  std::sort( _projects.begin(), _projects.end(), sortProject() );
}


void ProjectSorter::move( long src, long dst )
{
  Project* srcPrj = NULL;

  for( Projects::iterator it = _projects.begin(); it != _projects.end(); it++ )
  {
    if( (*it)->getSortPos() == src )
    {
      srcPrj = (*it);
      _projects.erase(it);
      break;
    }
  }
  assert(srcPrj);

  for( Projects::iterator it = _projects.begin(); it != _projects.end(); it++ )
  {
    if( (*it)->getSortPos() == dst )
    {
      // move up
      if( src > dst )
      {
        _projects.insert(it, srcPrj);
      }
      // move down
      else
      {
        _projects.insert(++it, srcPrj);
      }
      break;
    }
  }

  cleanupSortPositions();
}

void ProjectSorter::cleanupSortPositions()
{
  long sortpos = 0;
  for( Projects::iterator it = _projects.begin(); it != _projects.end(); it++ )
  {
    (*it)->setSortPos(sortpos);
    sortpos++;
  }
}

const Projects& ProjectSorter::getProjects() const
{
  return _projects;
}
