// This file is part of the Coral project.
// Please read the copyright notice in the LICENSE file.

#include "xmlns_conversion_table.h"
#include <stdlib.h>
#include <coral/lib/assert.h>

#include <set>
#include <algorithm>

#include <iostream>

namespace coral {
	
	struct cmp_xmlns {
	public:
		bool operator()(const coral::xmlns_conversion_entry& x,
				const coral::xmlns_conversion_entry& y)
			const throw () {
			return x.xmlns < y.xmlns;
		}
	};

	typedef std::set<coral::xmlns_conversion_entry,
			 cmp_xmlns> table_t;

	NAMESPACE_BEGIN();
	table_t table;
	NAMESPACE_END();

	bool addXMLNSRmap(const std::string& xmlns,
			  const std::string& filename,
			  const std::string& metamodelname,
			  int version,
			  int revision) {
		try {
			struct xmlns_conversion_entry t;
			t.xmlns = xmlns;
			t.smd_model_filename = filename;
			t.metamodelname = metamodelname;
			t.version = version;
			t.revision = revision;
			table_t::iterator i = table.find(t);
			if (i != table.end()) {
				if (*i != t) return false;
				return true;
			}
			// dlog << DEBUGLEVEL_DEBUG << "Inserting " << xmlns << std::endl;
			table.insert(t);
		} catch(...) {
			return false;
		}
		return true;
	}


	bool getXMLNSRmap(struct xmlns_conversion_entry* fill_in) {
		coral_assert(fill_in);
		// dlog << DEBUGLEVEL_DEBUG << "Trying to find " << fill_in->xmlns << std::endl;
		table_t::iterator i = table.find(*fill_in);
		if (i == table.end()) return false;
		*fill_in = *i;
		return true;
	}

	int xmlns_db_size() {
		return table.size();
	}

	std::string xmlns_db_xmlns(int idx) {
		coral_assert((0 <= idx) && (idx < xmlns_db_size()));
		table_t::const_iterator i = table.begin();
		std::advance(i, idx);
		return (*i).xmlns;
	}
	std::string xmlns_db_filename(int idx) {
		coral_assert((0 <= idx) && (idx < xmlns_db_size()));
		table_t::const_iterator i = table.begin();
		std::advance(i, idx);
		return (*i).smd_model_filename;
	}
	std::string xmlns_db_metamodelname(int idx) {
		coral_assert((0 <= idx) && (idx < xmlns_db_size()));
		table_t::const_iterator i = table.begin();
		std::advance(i, idx);
		return (*i).metamodelname;
	}
	int xmlns_db_version(int idx) {
		coral_assert((0 <= idx) && (idx < xmlns_db_size()));
		table_t::const_iterator i = table.begin();
		std::advance(i, idx);
		return (*i).version;
	}
	int xmlns_db_revision(int idx) {
		coral_assert((0 <= idx) && (idx < xmlns_db_size()));
		table_t::const_iterator i = table.begin();
		std::advance(i, idx);
		return (*i).revision;
	}

}
