//          Copyright Chris Josten 2020
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          https://www.boost.org/LICENSE_1_0.txt)
import std.functional;

import vibe.vibe;

import kerstezelprotocol;



struct VertaalContext {
	import std.typetuple;
	// Throw an error when an translation string is missing/mistyped.
	enum enforceExistingKeys = true;
	// The list of supported languages (the same family of languages will
	// automatically be matched to the closest candidate, e.g. en_GB->en_US)
	alias languages = TypeTuple!("en_GB", "nl_NL");
	// The base name of the translation files - the full names will be
	// kerstman.en_US.po and kerstman.de_DE.po. Any number of these mixin
	// statements can be used.
	mixin translationModule!"kerstman";
}

@translationContext!VertaalContext
class KerstezelService {

		@path("/")
		void getIndex() {
				render!"index.dt";
		}
		
		@path("/arreslee")
		void getArreslee(scope WebSocket bus) {
				runTask((WebSocket bus) {
						while(bus.connected) {
								string commando = bus.receiveText;
								if (commando == "trommel") {
										kerstmanTaak.send(TrommelCommando());
								} else {
										logInfo("Onbekend commando:" ~ commando);
								}
						}
				}, bus);

				while (bus.connected) {
						int uitzend_aantal = staatGebeurtenis.emitCount;
						bus.send(staat.serializeToJsonString());
						// Wordt elke 30 seconden wakker om de verbinding in leven
						// te houden en/of te detecteren dat deze juist gestopt is.
						staatGebeurtenis.wait(30.seconds, uitzend_aantal);
				}
		}

}


void main() {
	import vibe.http.router;

	auto settings = new HTTPServerSettings;
	settings.port = 8090;
	settings.bindAddresses = ["::", "0.0.0.0"];

	auto router = new URLRouter;
	router.registerWebInterface(new KerstezelService);

	auto fsettings = new HTTPFileServerSettings;
	fsettings.serverPathPrefix = "/statisch";
	router.get("*", serveStaticFiles("statisch/", fsettings));

	listenHTTP(settings, router);

	logInfo("Please open http://127.0.0.1:8080/ in your browser.");
	if (!listenTCP(9305, toDelegate(&kerstezelProtocolLuister), "0.0.0.0")) {
		logWarn("Kon kerstezelProtocol niet starten");
	}
	runApplication();
}
