/* ====================================================================
 * Copyright (c) 2006,      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;
};

static TargetRepositoryData* data = NULL;

void TargetRepository::setup()
{
  data = new TargetRepositoryData();
}

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);
}


syntax highlighted by Code2HTML, v. 0.9.1