/* ====================================================================
 * Copyright (c) 2003-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 "DiffInfoModelImpl.h"

// sys
#include <assert.h>


static DiffInfo NullDiffInfo( ctCommon, 0, BlockInfo() );


DiffInfoModelImpl::DiffInfoModelImpl()
: _activeDiff(0), _cntConflicts(0)
{
}

DiffInfoModelImpl::~DiffInfoModelImpl()
{
  // todo cleanup..
}

DiffInfos& DiffInfoModelImpl::getInfos()
{
  return _infos;
}

DiffInfo& DiffInfoModelImpl::getInfo( int numBlock )
{
  if( numBlock <= 0 || numBlock > (int)_infos.size() )
  {
    //printf("ups, bad numBlock in DiffInfoModelImpl::getInfo().");
    return NullDiffInfo;
  }

  return _infos[numBlock-1];
}

DiffInfo& DiffInfoModelImpl::getDiffInfo( int numDiff )
{
  TMapDiffNumToBlockNum::iterator it = _mapDiffNum.find(numDiff);

  if( it == _mapDiffNum.end() )
  {
    throw "ging nicht..";
  }
  
  return getInfo( (*it).second );
}

const BlockInfo& DiffInfoModelImpl::getBlockInfo( int numBlock )
{
  return getInfo(numBlock).getBlockInfo();
}

const BlockInfo& DiffInfoModelImpl::getDiffBlockInfo( int numDiff )
{
  return getDiffInfo(numDiff).getBlockInfo();
}

void DiffInfoModelImpl::addDiffInfo( const DiffInfo& info )
{
  DiffInfo i(info);

  if( info.getType() != ctCommon )
  {
    i.setDiffNumber( (int)(_mapDiffNum.size()+1) );

    _mapDiffNum.insert(
      TMapDiffNumToBlockNum::value_type(i.getDiffNumber(),i.getBlockNumber()) );
  }

  _infos.push_back(i);
}

TextModel* DiffInfoModelImpl::getModel( DiffInfoModel::DiffModel dm )
{
  return _models[dm];
}

void DiffInfoModelImpl::setModel( DiffInfoModel::DiffModel dm, TextModel* m )
{
  _models[dm] = m;
}

void DiffInfoModelImpl::setConflictCnt( int cnt )
{
  _cntConflicts = cnt;
}

int DiffInfoModelImpl::getDiffCnt()
{
  return (int)_mapDiffNum.size();
}

int DiffInfoModelImpl::getConflictCnt()
{
  return _cntConflicts;
}

int DiffInfoModelImpl::setActiveDiff( int num )
{
  assert( num >= 0 );
  assert( num <= getDiffCnt() );

  _activeDiff = num;

  return getDiffInfo( _activeDiff ).getBlockNumber();
}

int DiffInfoModelImpl::getActiveDiff()
{
  return _activeDiff;
}

int DiffInfoModelImpl::nextDiff()
{
  if( hasNextDiff() )
  {
    _activeDiff++;
  }
  else
  {
    _activeDiff = getDiffCnt(); 
  }

  return getDiffInfo( _activeDiff ).getBlockNumber();
}

int DiffInfoModelImpl::prevDiff()
{
  if( hasPrevDiff() )
  {
    _activeDiff--;
  }
  else
  {
    _activeDiff = 1;
  }

  return getDiffInfo( _activeDiff ).getBlockNumber();
}

bool DiffInfoModelImpl::hasPrevDiff()
{
  return _activeDiff > 1;
}

bool DiffInfoModelImpl::hasNextDiff()
{
  return _activeDiff < getDiffCnt();
}
