#include "gpx.h"
#include "cache.h"
#include "debug.h"

#include <iostream>
#include <fstream>
#include <string>
#include <gpx/GPX.h>
#include "gpx/Parser.h"
#include "gpx/Report.h"

class ReportDebug : public gpx::Report {
public:
	ReportDebug() {}
	~ReportDebug() {}
	void report(const gpx::Node* node, gpx::Report::Warning warning, const std::string& extra) {
		std::string msg;

		if (node != nullptr) {
			msg += (node->getType() == gpx::Node::ATTRIBUTE ? "Attribute " : "Element ") + node->getName() + " : ";
		}

		msg += gpx::Report::text(warning);

		if (!extra.empty()) {
			msg += ": " + extra;
		}

		Debug(3) << msg + ".\n";
	}
};

GPX::GPX(const std::string& path) {
	std::ifstream stream(path);
	if (stream.is_open()) {
		ReportDebug report;
		gpx::Parser parser(&report);
		root = parser.parse(stream);

		if (root == nullptr) {
			Debug(1) << "Parsing of file " << path << " failed due to " << parser.errorText() << " on line " << parser.errorLineNumber() << " and column " << parser.errorColumnNumber() << '\n';
		} else {
			items = root->wpts().list();
		}
	}
}

GPX::~GPX() {
	delete root;
}

Caches GPX::get_user_caches(__attribute__((unused)) const std::string& uuid, __attribute__((unused)) int count) const {
	Caches list;

	for (auto& el : items) {
		if (el->sym().getValue() == "Geocache Found") {
			Cache c;
			c.code = el->name().getValue();
			c.name = el->desc().getValue();
			c.pos.lat = stof(el->lat().getValue());
			c.pos.lon = stof(el->lon().getValue());
			c.type = el->type().getValue();
			if (c.type.starts_with("Geocache|"))
				c.type.erase(0, 9);
			if (c.type.ends_with(" Cache"))
				c.type.erase(c.type.end() - 6, c.type.end());
			if (c.type.ends_with("-cache"))
				c.type.erase(c.type.end() - 6, c.type.end());
			if (c.type == ("unknown"))
				c.type = "Unknown";

			if (c.code.starts_with("GC"))
				c.origin = "GC";
			else if (c.code.starts_with("OP"))
				c.origin = "OC.pl";
			else if (c.code.starts_with("TR") || c.code.starts_with("VI") || c.code.starts_with("MV"))
				c.origin = "GC.su";

			list.push_back(c);
		}
	}
	Debug(2) << "Caches read from GPX file: " << list.size() << '\n';

	return list;
}
