#include "name_resolver.h"
#include "exception.h"

#include <iostream>


bool name_resolver::exists(const aka::qname &name) const {
  pairs::const_iterator it = pairs_.find(name);
  return (!(it == pairs_.end()));
}

const aka::qname& name_resolver::resolve(const aka::qname &name) const {
  pairs::const_iterator it = pairs_.find(name);
  if (it == pairs_.end()) {
    std::string msg = std::string("Could not resolve \"") + name.qualified() + "\".";
    throw fatal_error(msg.c_str(), __FILE__, __LINE__);
  }
  return it->second;
}

void name_resolver::add(const aka::qname &name) {
  pairs_.insert(pairs::value_type(name, aka::qname()));
}

void name_resolver::add(const aka::qname &name, const aka::qname& t) {
  pairs::iterator it = pairs_.find(name);
  if (it != pairs_.end()) {
    if (!it->second.empty()) {
      std::cerr << it->second << std::flush;
      throw fatal_error();
    }
    it->second = t;// check delete.
  }
  else
    pairs_.insert(pairs::value_type(name, t));
}

void name_resolver::erase(const aka::qname &name) {
  pairs::iterator it = pairs_.find(name);
  if (it == pairs_.end())
    throw fatal_error();
  pairs_.erase(it);
}

void name_resolver::replace(const aka::qname &name, const aka::qname &newname) {
  pairs_[name] = newname;
}
