#include "ini.h"
#include "util.h"

ini_category const ini_category::empty;

std::string const& ini_category::get_string(std::string const& entry) const {

	if(_data.contains(entry))
		return _data.at(entry);
	return std::string("");
}

ini::ini(resource_manager& rm, ini_category const* ini, std::string const& path, std::vector<uint8_t> data) {
	std::istringstream stream(std::string(data.begin(), data.end()));
	std::string line, category("");

	while(std::getline(stream, line)) {
		line = trim(line);
		if(line.empty())
			continue;
		if(line.front() == ';')
			continue;
		if(line.size() >= 2 && line.front() == '[' && line.back() == ']')
			category = line.substr(1, line.size() - 2);
		auto eq_pos = line.find('=');
		if(eq_pos != std::string::npos) {
			auto left = trim(line.substr(0, eq_pos - 1));
			auto right = trim(line.substr(eq_pos + 1));
			_data[category]._data[left] = right;
		}
	}
}

ini_category const* ini::get_category(std::string const& name) const {
	if(_data.contains(name))
		return &_data.at(name);
	else
		return &ini_category::empty;
}
