/* -*- c++ -*- */
#include "osixaka.h"

#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdlib.h>

#include "ltg.h"
#include "name_resolver.h"
#include "generator.h"

bool test_parse_ok(const ltg::file &f) {
  osixaka osi(std::cerr);
  if (osi.parse(f.get_filepath()) != 0)
    return false;
  if (osi.process() != 0)
    return false;
  osi.akaxisonize();
  osi.generate("./");
  return true;
}

bool test_parse_ng(const ltg::file &f) {
  std::ostringstream ostm;

  try {
    osixaka osi(ostm);
    if (osi.parse(f.get_filepath()) != 0)
      return true;
    if (osi.process() != 0)
      return true;
    osi.akaxisonize();
    osi.generate("./");
  }
  catch ( ... ) {
    return true;
  }
  return false;
}


int main(int argc, char* argv[]){

  aka::initialize();
  // Initialize XML-Schema Document Classes.
  ltg::instantiate_xiso();
  osixaka::initialize();

  int total = 0;
  int ok = 0;

  aka::xml_parser parser;
  aka::document ltgdoc = parser.parse_file(argv[1]);
  ltg::root *root = aka::root_cast<ltg::root>(ltgdoc);
  const ltg::tests &tests = root->tests_;

  for (ltg::tests::const_iterator testit = tests.begin();
       testit != tests.end(); ++testit) {
    const ltg::files &fs = testit->files_;
    for (ltg::files::const_iterator fileit = fs.begin();
	 fileit != fs.end(); ++fileit) {
      bool res;
      bool done = false;

      if (fileit->validity_ && (fileit->role_ == "schema")) {
	res = test_parse_ok(*fileit);
	done = true;
      }
      else if (!fileit->validity_ && (fileit->role_ == "schema")) {
	res = test_parse_ng(*fileit);
	done = true;
      }

      if (done) {
	if (res) {
	  ++ok;
	  std::cout << '.' << std::flush;
	}
	else {
	  std::cout << std::endl
		    << "Failure:" << fileit->get_filepath() << std::endl;
	} 
	++total;
      }
    }
  }

  std::cout << std::endl
	    << argv[1] << std::endl
	    << "total: " << total 
	    << "  ok: " << ok << "  fail: " << total - ok << std::endl;

  // Uninitializers.
  aka::uninitialize();
  return 0;
}
