namespace ns_control
{
	
	/**
	 * ugly hack to prevent multiple listener addition
	 */
	function register_listener
	(
		dom_element: HTMLElement,
		eventname: string,
		handler: (event)=>void
	): void
	{
		const classname: string = `has_listener_for_${eventname}`;
		if (! dom_element.classList.contains(classname))
		{
			dom_element.addEventListener(eventname, handler);
			dom_element.classList.add(classname);
		}
		else
		{
			// do nothing
		}
	}
	
	
	/**
	 * sets up the control
	 */
	export function setup
	(
		conf: type_conf,
		model: type_model
	): void
	{
		// connect
		{
			register_listener
			(
				document.querySelector<HTMLFormElement>("#connect > form"),
				"submit",
				(e) =>
				{
					e.preventDefault();
					const nickname: string = document.querySelector<HTMLInputElement>("#nickname").value;
					const channel_names: Array<string> = document.querySelector<HTMLInputElement>("#channel").value.split(",");
					ns_model.connect(conf, model, nickname, channel_names);
				}
			);
		}
		// disconnect
		{
			register_listener
			(
				document.querySelector<HTMLButtonElement>("#disconnect"),
				"click",
				(e) =>
				{
					ns_model.disconnect(conf, model);
				}
			);
		}
		// send
		{
			register_listener
			(
				document.querySelector("#main > form"),
				"submit",
				(e) =>
				{
					e.preventDefault();
					const content: string = document.querySelector<HTMLInputElement>("#content").value;
					ns_model.send(conf, model, content);
				}
			);
		}
		// switch spot
		{
			document.querySelectorAll(".spot").forEach
			(
				(dom_spot) =>
				{
					register_listener
					(
						(dom_spot as HTMLElement),
						"click",
						(e) =>
						{
							const spot: type_spot = JSON.parse(dom_spot.getAttribute("rel"));
							ns_model.set_active(model, spot);
						}
					);
				}
			);
		}
		// open query
		{
			document.querySelectorAll(".user").forEach
			(
				(dom_user) =>
				{
					register_listener
					(
						(dom_user as HTMLElement),
						"click",
						(e) =>
						{
							const user_name: string = JSON.parse(dom_user.getAttribute("rel"));
							ns_model.open_query(model, user_name);
						}
					);
				}
			);
		}
	}
	
}