use fmt;
use dirs;
use format::ini;
use time::chrono;
use path;
use io;
use fs;
use os;
use errors;
use strings;

type config = struct {
	tz: chrono::locality,
};

type noexist = !str;

type conferror = !(path::error | noexist | fs::error | chrono::tzdberror);

fn loadconfig() (config | conferror) = {
	const confdir = dirs::config("distamp");
	const buf = path::init()?;
	const confpath = path::push(&buf, confdir, "config.ini")?;
	const f = match (os::open(confpath)) {
	case let e: errors::noentry =>
		fmt::errorln("warn: No config file found")!;
		return config {
			tz = chrono::LOCAL,
		};
	case let e: fs::error =>
		return e;
	case let f: io::file =>
		yield f;
	};
	defer io::close(f)!;
	const sc = ini::scan(f);

	let tz: chrono::locality = chrono::LOCAL;
	for (const e => ini::next(&sc)!) {
		const key = strings::trim(e.1);
		const val = strings::trim(e.2);
		if (key == "tz") {
			tz = chrono::tz(val)?;
		};
	};
	return config {
		tz = tz,
	};
};

fn strconferror(e: conferror) str = {
	match (e) {
	case let e: path::error =>
		return path::strerror(e);
	case let e: fs::error =>
		return fs::strerror(e);
	case let e: chrono::tzdberror =>
		return chrono::strerror(e);
	};
};
