#include "internal.h"

#include <regex>
#include <iostream>

int EventState::get(const struct event *e) const
{
	auto iter = this->state.find(e);

	if (iter == this->state.end())
		return 0;

	return iter->second;
}

void EventState::set(struct event *event, int val)
{
	this->state[event] = val;
}

void EventState::set(const std::string &name, int val)
{
	int i;
	struct event *e = NULL;

	for (i = 0; events_list[i]; i++) {
		if (events_list[i]->name == name) {
			e = events_list[i];
			break;
		}
	}

	if (!e)
		throw std::runtime_error(std::string("Invalid event name ") +
					 name);

	this->set(e, val);
}

void EventState::set_from_line(const std::string &line)
{
	std::regex state_regex("^(\\w+):\\s+([^\\s]+)\\s+\\((\\d+)\\)$");
	std::regex raw_regex("^(\\w+)\\((\\d+)\\):\\s+([+\\-]?\\d+)$");
	std::smatch sm;

	if (std::regex_match(line, sm, state_regex)) {
		this->set(sm[1], std::stoi(sm[3]));
	} else if (std::regex_match(line, sm, raw_regex)) {
		this->set(sm[1], std::stoi(sm[3]));
	} else {
		throw std::runtime_error(std::string("Invalid line: ") + line);
	}
}