
#include "settings.h"
#include "exception.h"
#include "ml_date.h"

namespace usql {

std::vector<std::pair<std::string, std::string>> Settings::m_settings =
	    { std::make_pair("DATE_FORMAT", "%Y-%m-%d"),
	      std::make_pair("BOOL_TRUE_LITERAL", "Y"),
	      std::make_pair("BOOL_FALSE_LITERAL", "N"),
	      std::make_pair("DOUBLE_FORMAT", "%.2f") };


long Settings::string_to_date(const std::string &datestr) {
	return ::string_to_date(datestr, get_setting("DATE_FORMAT"));
}


std::string Settings::date_to_string(long date) {
	return ::date_to_string(date, get_setting("DATE_FORMAT"));
}

std::string Settings::double_to_string(double d) {
	char buffer[32];
	int r, buf_size = 32;

	r = snprintf(buffer, buf_size, get_setting("DOUBLE_FORMAT").c_str(), d);
	if (r > 0 && r < buf_size) return std::string(buffer);

	return "ERROR";
}

std::string Settings::get_setting(const std::string &name) {
	for(const auto& pair : m_settings) {
		if (pair.first == name) return pair.second;
	}
	throw Exception("unsupported setting name: " + name);
}

void Settings::set_setting(const std::string &name, const std::string &value) {
	for (auto it = begin(m_settings); it != end(m_settings); ++it) {
		if (it->first == name)  {
			*it = std::make_pair(name, value); 
			return;
		}
	}	
	throw Exception("unsupported setting name: " + name);
}

}	//  namespace