#include "okapi.h"
#include "cache.h"
#include "debug.h"
#include "common.h"

#include <string>
#include <set>

void show_usage() {
	std::cout << "Usage: geolist list_of_caches\n";
	std::cout << "Produce a HTML list of caches given their OC codes.\n\n";
	std::exit(EXIT_FAILURE);
}

int main(int argc, char** argv) {
#include "config_user.h"

	if (argc == 1) show_usage();

	Caches cc;
	std::set<std::string> code_pl, code_de, code_us, code_nl, code_ro, code_uk;

	for (int i = 1; i < argc; i++) {
		if (argv[i][0] != 'O') continue;
		switch (argv[i][1]) {
			case 'P':
				code_pl.insert(argv[i]);
				break;
			case 'C':
				code_de.insert(argv[i]);
				break;
			case 'U':
				code_us.insert(argv[i]);
				break;
			case 'B':
				code_nl.insert(argv[i]);
				break;
			case 'R':
				code_ro.insert(argv[i]);
				break;
			case 'K':
				code_uk.insert(argv[i]);
				break;
		}
	}

	if (!code_pl.empty()) {
		Okapi OCpl(ocpl);
		Caches tmp = OCpl.get_caches(code_pl);
		std::copy(tmp.begin(), tmp.end(), std::back_inserter(cc));
	}
	if (!code_de.empty()) {
		Okapi OCde(ocde);
		Caches tmp = OCde.get_caches(code_de);
		std::copy(tmp.begin(), tmp.end(), std::back_inserter(cc));
	}
	if (!code_us.empty()) {
		Okapi OCus(ocus);
		Caches tmp = OCus.get_caches(code_us);
		std::copy(tmp.begin(), tmp.end(), std::back_inserter(cc));
	}
	if (!code_nl.empty()) {
		Okapi OCnl(ocnl);
		Caches tmp = OCnl.get_caches(code_nl);
		std::copy(tmp.begin(), tmp.end(), std::back_inserter(cc));
	}
	if (!code_ro.empty()) {
		Okapi OCro(ocro);
		Caches tmp = OCro.get_caches(code_ro);
		std::copy(tmp.begin(), tmp.end(), std::back_inserter(cc));
	}
	if (!code_uk.empty()) {
		Okapi OCuk(ocuk);
		Caches tmp = OCuk.get_caches(code_uk);
		std::copy(tmp.begin(), tmp.end(), std::back_inserter(cc));
	}

	header_html();

	std::cout << "<table class=\"list\">\n";
	std::cout << "<tr><th></th>";
	std::cout << "<th>Cache</th>";
	std::cout << "<th>Type</th>";
	std::cout << "<th>D/T</th>";
	std::cout << "<th>Date hidden</th>";
	std::cout << "<th>Owner</th>";
	std::cout << "<th>Region</th>";
	std::cout << "</tr>\n";

	short int n = 1;
	for (const auto& i : cc) {
		std::cout << "<tr><th>" << n << "</th> ";
		std::cout << "<td>" << i.link_name() << "</td>";
		std::cout << "<td>" << i.type << "</td>";
		std::cout << "<td>" << i.diff << '/' << i.terr << "</td>";
		std::cout << "<td>" << i.date_hidden << "</td>";
		std::cout << "<td>" << i.owner << "</td>";
		std::cout << "<td>" << i.region << "</td>";
		std::cout << "</tr>\n";
		n++;
	}
	std::cout << "</table>\n";

	footer_html();
}
