#include "simplecontent_handler.h"
#include "sequence_handler.h"
#include "simplecontent_handler.h"
#include "../classes/member_cache.h"

#include <cassert>
#include <sstream>

using namespace aka2;
  
simplecontent_handler::simplecontent_handler(const qname &tagname, void *sim, int depth, 
					     const simplecontent_op &sop, 
					     parser_context &context) 
  : handler(context, depth, tagname), sim_(sim), sop_(sop) {
}


parse_result simplecontent_handler::query_element(const qname &tagname, 
						  const attribute_values &attrs) {
  assert(!"Must not be called.");
  return ok;
}

parse_result simplecontent_handler::query_next(const qname &tagname, 
					       const attribute_values &attrs) {
  assert(!"Must not be called.");
  return ok;
}


parse_result simplecontent_handler::end_element(const qname &tagname) {
  return ok;
}


bool simplecontent_handler::parse_entity(const std::string &entity) {
  std::istringstream istm(entity);
  const member_type &vtype = sop_.get_valuetype();
  assert(vtype.get_schematype() == simpletype_id);
  member_cache cache(sim_, vtype.op(), vtype.getter());
  cache.prepare(false);

  try {
    static_cast<const simpletype_op&>(vtype.op()).
      read_text(cache.value(), istm, context_.get_preconditions());
    cache.flush();
    return true;
  }
  catch ( const std::exception &e ) {
    context_.report(e.what(), __FILE__, __LINE__);
  }
  catch ( ... ) {
    context_.report("Unhandled parse error on parsing entity.", __FILE__, __LINE__);
  }
  return false;
}

node simplecontent_handler::get_node() {
  return node(sim_, sop_);
}

void simplecontent_handler::receive_child(const node &child) {
  assert(!"Must not be called.");
}

bool simplecontent_handler::can_skip()  {
  return false;
}
