/* ====================================================================
 * 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 "IgnoreCmd.h"
#include "IgnoreParam.h"
#include "CmdResultCallback.h"
#include "CmdProgressCallback.h"
#include "svn/PropGetItem.h"
#include "svn/Revision.h"
#include "svn/Client.h"
#include "svn/Path.h"


IgnoreCmd::IgnoreCmd( IgnoreParam* param, CmdResultCallback* cb )
: ScCmd(param->getId()), _param(param), _cb(cb)
{
}

IgnoreCmd::~IgnoreCmd()
{
  delete _cb;
}

void IgnoreCmd::run()
{
  sc::Error* err;

  _prgscb->started( _param, getCancel() );

  const svn::Paths& paths = _param->getPaths();
  for( svn::Paths::const_iterator it = paths.begin(); it != paths.end(); it++ )
  {
    const sc::String& name = *it;

    sc::String basename = svn::Path::getBaseName(name);
    sc::String dirname  = svn::Path::getDirName(name);

    if( ! svn::Client::isWorkingCopy(dirname) )
    {
      // \todo error
    }

    svn::PropGetItems items;

    err = _client->propget(
      items, sc::String("svn:ignore"), dirname, svn::RevUnspecified, false );

    if( err )
      break;

    sc::String propValue;

    if( items.size() == 1 )
    {
      propValue = items.front()->getValue();
    }

    propValue += basename;
    propValue += "\n";

    err = _client->propset( sc::String("svn:ignore"), propValue, dirname, false );

    if( err )
      break;
  }

  _param->setError( err );
  _prgscb->finished( _param );

  _cb->handleResult( _param, err );
}
