/**
 *
 * @file src/trace/Serializer.cpp
 *
 * @copyright 2008-2024 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria,
 *                      Univ. Bordeaux. All rights reserved.
 *
 * @author Camille Ordronneau
 * @author Johnny Jazeix
 * @author Augustin Degomme
 *
 * @date 2024-07-17
 */
#include <iostream>
#include <utility>
#include <string>
#include <boost/bimap.hpp>
#include <QMutex>
using namespace std;

template <typename T>
void Serializer<T>::clear() {
    _map.clear();
}

template <typename T>
bool Serializer<T>::setUid(int n, const T *c) {
    _lock.lock();
    pair<typename boost::bimap<int, const T *>::iterator, bool> ret;
    ret = _map.insert(typename boost::bimap<int, const T *>::value_type(n, c));
    _lock.unlock();
    return ret.second;
}

template <typename T>
int Serializer<T>::setUid(const T *c) {
    static int static_uid = 0;
    _lock.lock();
    pair<typename boost::bimap<int, const T *>::iterator, bool> ret;
    ret = _map.insert(typename boost::bimap<int, const T *>::value_type(static_uid, c));

    if (ret.second == false) {
        // c already exists
        typename boost::bimap<int, const T *>::right_const_iterator it = _map.right.find(c);
        int t = -1;
        if (it != _map.right.end())
            t = (*it).second;
        _lock.unlock();
        return t;
    }
    static_uid++;
    _lock.unlock();
    return static_uid - 1;
}

template <typename T>
const T *Serializer<T>::getValue(int n) {
    _lock.lock();
    typename boost::bimap<int, const T *>::left_const_iterator it = _map.left.find(n);
    const T *t = NULL;
    if (it != _map.left.end())
        t = (*it).second;
    _lock.unlock();
    return t;
}

template <typename T>
int Serializer<T>::getUid(const T *c) {
    _lock.lock();
    typename boost::bimap<int, const T *>::right_const_iterator it = _map.right.find(c);
    int t = -1;
    if (it != _map.right.end())
        t = (*it).second;
    _lock.unlock();
    return t;
}
