/*!
  \file
  \brief タイムスタンプ管理

  \author Satofumi KAMIMURA

  $Id$
*/

#include "TimestampManager.h"
#include "Timestamp.h"
#include "ticks.h"
#include <algorithm>
#include <map>

using namespace qrk;
using namespace std;


namespace
{
    typedef map<Timestamp*, long> TimestampOffset;
}


struct TimestampManager::pImpl
{
    TimestampOffset objects_;
};


TimestampManager::TimestampManager(void) : pimpl(new pImpl)
{
}


TimestampManager::~TimestampManager(void)
{
}


void TimestampManager::add(Timestamp* object)
{
    pimpl->objects_[object] = 0;
}


void TimestampManager::remove(Timestamp* object)
{
    if (pimpl->objects_.empty()) {
        return;
    }

    TimestampOffset::iterator it = pimpl->objects_.find(object);
    if (it != pimpl->objects_.end()) {
        pimpl->objects_.erase(it);
    }
}


void TimestampManager::setTimestamp(long timestamp)
{
    long first_ticks = ticks();

    for (TimestampOffset::iterator it = pimpl->objects_.begin();
         it != pimpl->objects_.end(); ++it) {
        long raw_timestamp = it->first->timestamp();
        long called_ticks = ticks();

        it->second = (timestamp - raw_timestamp) + (called_ticks - first_ticks);
    }
}


long TimestampManager::timestamp(Timestamp* object)
{
    return timestamp(object, object->timestamp());
}


long TimestampManager::timestamp(Timestamp* object, long raw_timestamp)
{
    TimestampOffset::const_iterator it = pimpl->objects_.find(object);
    if (it == pimpl->objects_.end()) {
        return -1;
    }

    return raw_timestamp + it->second;
}
