
#include "ml_date.h"

long now() {
	// get-universal-time
	time_t t = std::time(0);
	long int now = static_cast<long int>(t);

	return now;
}

std::string date_to_string(const long datetime, const std::string format) {
	// std::locale::global(std::locale("en-US.UTF8"));

	time_t timestamp = datetime;
	char mbstr[128];

	if (std::strftime(mbstr, sizeof(mbstr), format.c_str(), std::localtime(&timestamp))) {
		std::string result = {mbstr};
		return result;
	}
	// TODO exception here
    return "invalid argument";
}

long string_to_date(const std::string &datestr, const std::string &format) {
	// format for example "%d.%m.%Y";

	std::istringstream in{datestr.c_str()};
	date::sys_seconds tp;
	in >> date::parse(format, tp);
	return tp.time_since_epoch().count();
}

long add_to_date(const long datetime, const long quantity, const std::string &part) {
	// part is one of 'year', 'month', 'day', 'hour', 'minute' or 'second'

	// very basic implementation, just for now - no timezones DST etc
	time_t base = datetime;
	struct tm *tm = localtime(&base);

	if (part == "year") {
		tm->tm_year += quantity;
	} else if (part == "month") {
		tm->tm_mon += quantity;
	} else if (part == "day") {
		tm->tm_mday += quantity;
	} else if (part == "hour") {
		tm->tm_hour += quantity;
	} else if (part == "minute") {
		tm->tm_min += quantity;
	} else if (part == "second") {
		tm->tm_sec += quantity;
	} else {
		// TODO exception here
	}

	return mktime(tm);
}
