/* ====================================================================
 * Copyright (c) 2006, 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 "LogGraphCmd.h"
#include "LogGraphParam.h"
#include "CmdResultCallback.h"
#include "CmdProgressCallback.h"
#include "svn/Client.h"
#include "svn/Revision.h"
#include "svn/InfoBaton.h"
#include "svn/LogBaton.h"
#include "svn/Info.h"
#include "svn/Error.h"


class InfoLogBaton : public svn::InfoBaton, public svn::LogBaton
{
public:
  InfoLogBaton( LogGraphBaton* baton ) : _baton(baton)
  {
  }

  // svn::InfoBaton
  void info( svn::InfoPtr info )
  {
    sc::String url  = info->getUrl();
    sc::String root = info->getRootUrl();
    url = url.right( url.getCharCnt()-root.getCharCnt() );
    if( url.isEmpty() )
      url = "/";

    _rootUrl = root;

    _baton->setUrlInfo( root, url );
  }

  // svn::LogBaton
  svn::Error* receiveMessage( const svn::LogEntryPtr log )
  {
    _baton->addLogMsg(log);

    return SVN_NO_ERROR;
  }

  const sc::String getRootUrl() const
  {
    return _rootUrl;
  }

private:
  LogGraphBaton* _baton;
  sc::String     _rootUrl;
};




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

LogGraphCmd::~LogGraphCmd()
{
}

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

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

  InfoLogBaton baton(_param->getBaton());

  svn::Revision rev(svn::Revision_Unspecified);
  err = _client->info( _param->getSource(), rev, svn::RevHead, &baton, false );

  if( err == sc::Success )
  {
    svn::RevisionNumber rev0(1);
    svn::Paths paths;
    paths.push_back(baton.getRootUrl());
    err = _client->log( paths, rev0, svn::RevHead, false, true, false, &baton );
  }

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

  _cb->handleResult( _param, err );
}
