// -*- c++ -*-

#include "tokenmap.h"
#include <cassert>

using namespace aka2;


const id_type aka2::unregistered_token = -1;
const id_type aka2::empty_token = 0;


id_type tokenmap::register_and_get_id(const std::string &ns_uri){
  id_type id = get_id(ns_uri);
  if (id != unregistered_token)
    return id;

  std::pair<ids::iterator, bool> res_idmap = 
    ids_.insert(ids::value_type(ns_uri, current_id_));
  assert(res_idmap.second);

  std::pair<tokens::iterator, bool> res_urimap = 
    tokens_.insert(tokens::value_type(current_id_, ns_uri));
  assert(res_urimap.second);

  ++current_id_;
  return res_idmap.first->second;
}


id_type tokenmap::get_id(const std::string &token) const{
  
  ids::const_iterator it = ids_.find(token);
  if (it == ids_.end())
    return unregistered_token;

  return it->second;

}

const std::string &tokenmap::get_token(const id_type id) const {
  tokens::const_iterator it = tokens_.find(id);
  if (it == tokens_.end())
      throw invalid_argument();
  return it->second;
}

//
//
//

void tokenmap::initialize(){
  ids_.clear();
  tokens_.clear();
  ids_.insert(ids::value_type("", empty_token));
  tokens_.insert(tokens::value_type(empty_token, ""));
}

void tokenmap::uninitialize() {
  ids_.clear();
  tokens_.clear();
}


//
//
//
void tokenassociation::associate(const id_type id, const std::string &token) {
  tokens::iterator it = tokens_.find(id);
  if (it != tokens_.end()) {
    if (token != it->second)
       throw invalid_argument();
    return;
  }

  tokens_.insert(tokens::value_type(id, token));
  ids_.insert(ids::value_type(token, id));
}

const std::string &tokenassociation::get_token(const id_type id) const {
  tokens::const_iterator it = tokens_.find(id);
  if (it == tokens_.end())
     throw invalid_argument();
  return it->second;
}

void tokenassociation::initialize(){
  tokens_.clear();
  ids_.clear();
}

void tokenassociation::uninitialize(){
  tokens_.clear();
  ids_.clear();
}



id_type tokenassociation::get_id(const std::string &token) const{
  ids::const_iterator it = ids_.find(token);
  if (it == ids_.end())
    return unregistered_token;
  return it->second;
}
