/* ====================================================================
 * 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 "TargetRepository.h"
#include "util/Mutex.h"
#include "util/Guard.h"

// sys
#include <map>
#include <cassert>


typedef std::map<unsigned long,QObject*>    TargetMap;
typedef std::pair<TargetMap::iterator,bool> ResPair;

class TargetRepositoryData
{
public:
  sc::Mutex targetMutex;
  TargetMap targetMap;
  ID        error;
};

static TargetRepositoryData* data = NULL;

void TargetRepository::setup()
{
  data = new TargetRepositoryData();
  data->error = 0;
}

void TargetRepository::teardown()
{
  delete data;
  data = NULL;
}

ID TargetRepository::create()
{
  return Id::next();
}

void TargetRepository::add( ID tid, QObject* o )
{
  sc::Guard<sc::Mutex> guard(data->targetMutex);

   ResPair p = data->targetMap.insert( TargetMap::value_type(tid,o) );

   if( ! p.second )
   {
     assert(false);
   }
}

QObject* TargetRepository::get( ID tid )
{
  sc::Guard<sc::Mutex> guard(data->targetMutex);

  TargetMap::iterator it = data->targetMap.find(tid);
  if( it != data->targetMap.end() )
  {
    return (*it).second;
  }
  else
  {
    return NULL;
  }
}

void TargetRepository::del( ID tid )
{
  sc::Guard<sc::Mutex> guard(data->targetMutex);

  data->targetMap.erase(tid);
}


void TargetRepository::setError( ID errortid )
{
  sc::Guard<sc::Mutex> guard(data->targetMutex);

  data->error = errortid;
}

QObject* TargetRepository::getError()
{
  return get(data->error);
}
