package org.devocative.wickomp.async;

import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.protocol.ws.WebSocketSettings;
import org.apache.wicket.protocol.ws.api.IWebSocketConnection;
import org.apache.wicket.protocol.ws.api.WebSocketBehavior;
import org.apache.wicket.protocol.ws.api.registry.IWebSocketConnectionRegistry;
import org.apache.wicket.protocol.ws.api.registry.PageIdKey;

import java.io.IOException;

public abstract class WTextAsyncBehavior extends WebSocketBehavior {
	private static final long serialVersionUID = -6196868642769507632L;

	// ------------------------------

	private static Application app;
	private String sessionId;
	private int pageId;

	// ------------------------------

	@Override
	public void bind(Component component) {
		app = component.getApplication();
		pageId = component.getPage().getPageId();
	}

	@Override
	public void afterRender(Component component) {
		sessionId = WebSession.get().getId();
	}

	// ---------------

	public void push(String text) {
		WebSocketSettings webSocketSettings = WebSocketSettings.Holder.get(app);
		IWebSocketConnectionRegistry registry = webSocketSettings.getConnectionRegistry();
		IWebSocketConnection connection = registry.getConnection(
			app,
			sessionId,
			new PageIdKey(pageId)
		);

		try {
			connection.sendMessage(text);
		} catch (IOException e) {
			throw new WicketRuntimeException(e);
		}
	}
}

@@ -525,16 +525,73 @@
 geIdKey;
+%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aimport
@@ -752,16 +752,106 @@
 7632L;%0A%0A
+%09private static final Logger logger = LoggerFactory.getLogger(WTextAsyncBehavior.class);%0A%0A
 %09// ----
@@ -1577,37 +1577,186 @@
 %0A%09%09%09
-connection.sendMessage(text);
+if (connection != null && connection.isOpen()) %7B%0A%09%09%09%09connection.sendMessage(text);%0A%09%09%09%7D else %7B%0A%09%09%09%09logger.warn(%22WTextAsyncBehavior.push: broken connection text=%5B%7B%7D%5D%22, text);%0A%09%09%09%7D
 %0A%09%09%7D

check connection and then send message