const api_creds = "queueview:queueview";
const api_app = "queueview"; //_" + (""+Math.random()).substring(2);

let ws;

let channels = {};

function render_channels() {
	const data = Object.keys(channels).sort((a,b) => channels[b].bid - channels[a].bid).map(
		channel => Object({"channel": channel, ...channels[channel]})
	);

	const channel_nodes = d3.select("#channels").selectAll('li');
        const channel_data = channel_nodes.data(
		data,
		info => `${info.channel}/${info.bid}/${info.caller.name}/${info.caller.number}`
	);

	channel_data.enter().append('li').html(
		info => `<span class="bid">${info.bid}</span> <span class="caller">${info.caller.name} ${info.caller.number}</span>`
	);
	channel_data.exit().remove();
	channel_data.order();
}

function message_handler(message) {
	var data = JSON.parse(message.data);
	console.debug(data);

	if (data.type == "ChannelVarset" && data.variable == "__AUCTION_BID") {
		/* Just entered queue */
		const bid = {
			caller: data.channel.caller,
			bid: data.value
		};

		console.info("Registered bid on channel:", bid, data.channel.name);
		channels[data.channel.name] = bid;
		render_channels();
	}

	if (data.type == "ChannelVarset" && data.variable == "QUEUEPOSITION") {
		/* Left queue */
		console.info("Caller left:", data.channel.name);
		delete channels[data.channel.name];
		render_channels();
	}
}

function open_socket() {
	const current_url = new URL(document.location.href);
	const ws_url = `ws://${current_url.host}/ari/events?api_key=${api_creds}&app=${api_app}&subscribeAll=true`;

	console.log("Opening socket...");
	ws = new WebSocket(ws_url);
	ws.addEventListener('message', message_handler);
}

open_socket();
