/* -*- c++ -*- */
#include "document.h"
#include "model_check.h"

using namespace aka2;

element_props &document_factory::register_document_type(const qname &docname, 
							const element_op& op){
  element_props props(op);
  props.set_name(docname);
  std::pair<doctype_map::iterator, bool> res = 
    doctype_map_.insert(doctype_map::value_type(docname, props));
  if (!res.second)
    throw internal_error();
  return res.first->second;
}


void document_factory::register_document_type(const qname &docname, 
					      const element_op& op,
					      const occurrence &occ){
  element_props &props = register_document_type(docname, op);
  if (!check_occurrence(op.get_schematype(), occ))
    throw internal_error();
  props.set_occurrence(occ);
}

void document_factory::register_document_type(const qname &docname, 
					      const element_op& op,
					      const std::string &defval){
  element_props &props = register_document_type(docname, op);
  if (!check_has_default(op.get_schematype()))
    throw internal_error();
  props.setup_default_value(defval);
}

document document_factory::create_named_document(const qname &docname){
  doctype_map::iterator it = doctype_map_.find(docname);
  if (it == doctype_map_.end()) {
    std::string errmsg = "Document(" + docname.qualified() + ") not found.";
    throw error(errmsg.c_str(), __FILE__, __LINE__);
  }
  void* root = it->second.op().create();

  return document(root, it->second);
}

const element_props& document_factory::get_props(const qname &docname) const {
  doctype_map::const_iterator it = doctype_map_.find(docname);
  if (it == doctype_map_.end())
    throw internal_error();
  return it->second;
}

bool aka2::document_of(const aka2::document &i, const std::string &tagname) {
  return aka2::qname(tagname) == i.get_name();
}
