#include "project.h"

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

void serialize() {
  
  // Get the root node.
  pj::Team team;
  pj::Members &members= team.members_;

  team.name_ = "Cuppa project team";
  team.url_ = "http://unittest.org";

  // Member
  pj::Member epi("Episteme", "God of dragon");
  members.push_back(epi);

  pj::Member shibu("Shibukawa", "Artistic director");
  members.push_back(shibu);

  pj::Member doukeshi("Doukeshi", "Wraith of the trickstar");
  members.push_back(doukeshi);

  pj::Member ahiru("Ahiru", "BCB guru");
  members.push_back(ahiru);

  pj::Member shelarcy("shelarcy", "RELAX NG Evangelist");
  members.push_back(shelarcy);

  pj::Member ando("Ando(&o)", "Sorcerer of macuppa");
  members.push_back(ando);

  pj::Member morino("Morino", "Farmer");
  members.push_back(morino);

  // Create Document instance.
  aka::xml_serializer ser;

  // Serialize.
  ser.serialize(team, "cuppa:project", std::cout);

}

void parse() {
  // 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, "cuppa:project")) {
    std::cerr << "Unknown document(" << doc.get_name() << ")." << std::endl;
    exit(1);
  }

  // Get the root node.
  pj::Team  *team = aka::root_cast<pj::Team>(doc);
  pj::Members &members = team->members_;

  // Title
  std::cout << "Member list of '" << team->name_ << "'(" << team->url_ << ')' << std::endl;

  // Row for each member.
  for (pj::Members::iterator it = members.begin();
       it != members.end(); ++it) 
    std::cout << "name : " << it->name_ 
              << std::string("                    ").substr(it->name_.size())
              << "title : " << it->title_ << 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();

  // Initialize Project classes defined in project.h.
  aka::xmlns("cuppa", "http://unittest.org/akaxiso/memberlist");
  aka::doctype("cuppa:project", xiso::leaf<pj::Team>());

  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;
}
