/* -*- c++ -*- */
#include "qname.h"
#include <cassert>

namespace aka2 {

void qname::set(const std::string &uri, const std::string &name) {
  uri_id_ = namespaces().get_namespace_id(uri);
  name_ = name;
}

void qname::set(const id_type uri_id, const std::string &name) {
  uri_id_ = uri_id;
  name_ = name;
}


void qname::set(const std::string &rawname, const global_attributes &gattrs) {
  std::string::size_type pos = rawname.find_first_of(':');

  if (pos == std::string::npos) { // local, not qualified.
    uri_id_ = empty_token;
    name_ = rawname;
  }
  else {
    std::string prefix = rawname.substr(0, pos);
    uri_id_ = gattrs.get_prefix_map().get_prefix_id(prefix);
    if (uri_id_ == unregistered_token)
      throw invalid_argument();
    name_ = rawname.substr(pos + 1, rawname.length() - pos);
  }
}

const std::string &qname::qualified(const global_attributes &gattrs) const{
  if (uri_id_ == unregistered_token) {
    cache_ = "";
    return cache_;  
  }
  if (is_qualified()) {
    cache_ = gattrs.get_prefix_map().get_prefix(uri_id_) + ':' + name_;
    return cache_;
  }
  else
    return name_;
}

const std::string &qname::local() const {
  return name_;
}

bool qname::empty() const {
  assert((uri_id_ != unregistered_token) || (name_.empty()));
  if (uri_id_ == unregistered_token)
    return true;
  return (name_.empty());
}

} // namespace aka2
