#include "intset.h"

#include <vector>
#include <string>
#include <cstdlib>
#include <regex>

std::vector<std::string> resplit(const std::string & s, std::regex rgx) {
	std::vector<std::string> ret;
	if(!std::regex_search(s, rgx)) {
		ret.push_back(s);
		return ret;
	} else {
		std::sregex_token_iterator iter(s.begin(), s.end(), rgx, -1);
		std::sregex_token_iterator end;
		while (iter != end) {
			ret.push_back(*iter);
			++iter;
		}
		return ret;
	}
}

std::set<int> intset(const std::string desc) {
	std::regex re_sep(","), re_range("([0-9]+)[-]([0-9]+)");
	auto strlist = resplit(desc, re_sep);
	std::set<int> ret;
	for(auto s : strlist) {
		std::smatch m;
		if(std::regex_match(s, m, re_range)) {
			int low = std::stoi(m[1]);
			int high = std::stoi(m[2]);
			for(int i=low;i<=high;i++) {
				ret.emplace(i);
			}
		} else {
			int lit = std::stoi(s);
			ret.emplace(lit);
		}
	}
	return ret;
}

std::unordered_map<int,int> intmap(const std::string desc) {
	std::regex re_sep(","), re_range("([0-9]+)[:]([0-9]+)");
	auto strlist = resplit(desc, re_sep);
	std::unordered_map<int,int> ret;
	for(auto s : strlist) {
		std::smatch m;
		if(std::regex_match(s, m, re_range)) {
			int from = std::stoi(m[1]);
			int to = std::stoi(m[2]);
			ret[from] = to;
		}
	}
	return ret;
}
