#include "ygg_parser.h"
#include "ygg_handler.h"
#include "../classes/scoped_ptr.h"
#include <sstream>
#include <fstream>

using namespace aka2;
namespace ygg = yggdrasil;

void ygg_parser::set_gattrs(global_attributes &gattrs) {
  gattrs_ = &gattrs;
}

document ygg_parser::parse(std::istream &istm) {
  return parse_internal(istm, "(std::istream)");
}

document ygg_parser::parse_stdin(){
  return parse_internal(std::cin, "(stdin)");
}

document ygg_parser::parse(const char *buff){
  std::istringstream istm(buff);
  return parse_internal(istm, "(membuf)");
}


document ygg_parser::parse(const std::string& document){
  std::istringstream istm(document);
  return parse_internal(istm, "(std::string)");
}

document ygg_parser::parse_file(const std::string &filename) {
  std::ifstream istm(filename.c_str());
  return parse_internal(istm, filename);
}

document yggsox_parser::parse_internal(std::istream &istm, const std::string &source_name) {
  scoped_ptr<ygg_handler> handler(new ygg_handler);
  handler->set_source_name(source_name);
  if (gattrs_ != 0)
    handler->set_gattrs(*gattrs_);
  ygg::sox_stream().read(istm, handler.get());
  document document = handler->get_document();
  handler.reset();
  return document;
}


document yggxml_parser::parse_internal(std::istream &istm, const std::string &source_name) {
  scoped_ptr<ygg_handler> handler(new ygg_handler);
  handler->set_source_name(source_name);
  if (gattrs_ != 0)
    handler->set_gattrs(*gattrs_);
  ygg::xml_stream().read(istm, handler.get());
  document document = handler->get_document();
  handler.reset();
  return document;
}

