import slf4d;
import handy_http_starter;

void main() {
	Http1TransportConfig transportConfig = defaultConfig();
	transportConfig.port = 8110;
	HttpTransport transport = new TaskPoolHttp1Transport(new AppHandler(), transportConfig);
	transport.start();
}

struct Entry {
	string partyName;
	string name;
	string comment;
}

class AppHandler : HttpRequestHandler {
	void handle(ref ServerHttpRequest request, ref ServerHttpResponse response) {
		response.headers.add("Access-Control-Allow-Origin", "*");
		response.headers.add("Access-Control-Allow-Methods", "*");
		response.headers.add("Access-Control-Allow-Headers", "Content-Type");

		if (request.method == HttpMethod.GET) {
			getEntries(request.getParamAs!string("party"), response);
		} else if (request.method == HttpMethod.POST) {
			auto payload = readJsonBodyAs!Entry(request);
			addEntry(payload);
		}
	}
}

void getEntries(string partyName, ref ServerHttpResponse response) {
	import std.file;
	import std.path;
	import std.json;
	const filename = buildPath("data", partyName ~ ".json");
	if (!exists(filename)) {
		response.writeBodyString("[]", ContentTypes.APPLICATION_JSON);
		return;
	}
	JSONValue root = parseJSON(readText(filename));
	response.writeBodyString(root.object["entries"].toJSON(), ContentTypes.APPLICATION_JSON);
}

void addEntry(in Entry payload) {
	import std.file;
	import std.path;
	import std.json;
	if (!exists("data")) mkdir("data");
	const filename = buildPath("data", payload.partyName ~ ".json");
	if (!exists(filename)) {
		JSONValue obj = JSONValue.emptyObject;
		obj.object["entries"] = JSONValue.emptyArray;
		write(filename, obj.toPrettyString());
	}
	JSONValue root = parseJSON(readText(filename));
	JSONValue node = JSONValue.emptyObject;
	node.object["name"] = JSONValue(payload.name);
	node.object["comment"] = JSONValue(payload.comment);
	root.object["entries"].array ~= node;
	write(filename, root.toPrettyString());
	info("Added entry.");
}
