#include "model_array.h"

#include <akaxiso/akaxiso.h>
#include <iostream>
#include <stdlib.h>

void serialize() {

  root models;
  model m;
  m.test_ = "test1";
  models.models_.push_back(m);

  m.test_ = "test2";
  models.models_.push_back(m);

  aka::xml_serializer ser;
  ser.serialize(models, "model_arrays", std::cout);
}

void parse() {

  aka::xml_parser parser;

  aka::document doc;
  try {
    doc = parser.parse_stdin();
  }
  catch ( const std::exception &e) {
    std::cerr << e.what() << std::endl;
    exit(1);
  }
  catch ( ... ) {
    std::cerr << "Parse error detected." << std::endl;
    exit(1);
  }
  
  // Check root tagname to confirm the root class.
  if (!aka::document_of(doc, "model_arrays")) {
    std::cerr << "Unknown document(" << doc.get_name() << ")." << std::endl;
    exit(1);
  }

  // Get the root node.
  root *models = aka::root_cast<root>(doc);

  for (model_array::iterator iter = models->models_.begin(); iter != models->models_.end(); ++iter)
    std::cout << iter->test_ << std::endl;
}


void usage() {
  std::cout << "project [-s|-p|-h]" << std::endl
            << "  -s : serialize." << std::endl
            << "  -p : parse.    " << std::endl
            << "  -h : show this usage." << std::endl;
}


int main(int argc, const char* argv[]){
  
  aka::initialize();
  aka::doctype("model_arrays", xiso::leaf<root>());

  if (argc != 2) {
    usage();
    return 1;
  }

  std::string arg = argv[1];

  if (arg == "-s")
    serialize();
  else if (arg == "-p")
    parse();
  else {
    usage();
    return 1;
  }

  aka::uninitialize();
  return 0;
}
