package at.irian.ankorsamples.todosample.fxclient;

import at.irian.ankor.fx.controller.FXControllerChangeListener;
import at.irian.ankor.messaging.json.viewmodel.ViewModelJsonMessageMapper;
import at.irian.ankor.ref.RefContext;
import at.irian.ankor.ref.RefFactory;
import at.irian.ankor.servlet.websocket.messaging.WebSocketMessageBus;
import at.irian.ankor.servlet.websocket.session.WebSocketRemoteSystem;
import at.irian.ankor.session.SingletonSessionManager;
import at.irian.ankor.system.AnkorSystem;
import at.irian.ankor.system.AnkorSystemBuilder;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.UUID;

/**
 * @author Thomas Spiegl
 */
public class App extends Application {
    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(App.class);

    private static RefFactory refFactory;
    private static HostServices services;
    private boolean connected = false;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        services = getHostServices();
        createWebSocketClientSystem(primaryStage);
        //startFXClient(primaryStage);
    }

    private void startFXClient(Stage primaryStage) throws IOException {
        primaryStage.setTitle("Ankor FX Sample");
        Pane myPane = FXMLLoader.load(getClass().getClassLoader().getResource("tasks.fxml"));

        Scene myScene = new Scene(myPane);
        myScene.getStylesheets().add("style.css");
        primaryStage.setScene(myScene);
        primaryStage.show();
    }

    private void createWebSocketClientSystem(final Stage primaryStage) throws IOException, DeploymentException {
        final String clientId = UUID.randomUUID().toString();

        final AnkorSystem[] clientSystem = new AnkorSystem[1];
        final WebSocketMessageBus messageBus = new WebSocketMessageBus(new ViewModelJsonMessageMapper());
        final AnkorSystemBuilder systemBuilder = new AnkorSystemBuilder()
                .withName(clientId)
                .withGlobalEventListener(new FXControllerChangeListener())
                .withMessageBus(messageBus)
                .withModelContextId("collabTest");

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://localhost:8080" + "/websocket/ankor/" + clientId;
        container.connectToServer(new Endpoint() {

            @Override
            public void onOpen(Session session, EndpointConfig config) {
                session.addMessageHandler(new MessageHandler.Whole<String>() {

                    @Override
                    public void onMessage(String message) {
                        messageBus.receiveSerializedMessage(message);
                    }
                });

                messageBus.addRemoteSystem(new WebSocketRemoteSystem(clientId, session));
                final AnkorSystem clientSystem = systemBuilder.createClient();
                RefContext clientRefContext = ((SingletonSessionManager) clientSystem.getSessionManager()).getSession().getRefContext();
                refFactory = clientRefContext.refFactory();
                try {
                    startFXClient(primaryStage);
                } catch (IOException ignored) {
                }
            }
        }, URI.create(uri));
    }

    public static HostServices getServices() {
        return services;
    }

    public static RefFactory refFactory() {
        return refFactory;
    }
}
@@ -848,41 +848,90 @@
 ID;%0A
-%0A/**%0A * @author Thomas Spiegl%0A */
+import java.util.concurrent.CountDownLatch;%0Aimport java.util.concurrent.TimeUnit;%0A
 %0Apub
@@ -1379,16 +1379,43 @@
 %0A       
+ AnkorSystem clientSystem =
  createW
@@ -1435,39 +1435,210 @@
 tSystem(
-primaryStage
+);%0A%0A        RefContext clientRefContext = ((SingletonSessionManager) clientSystem.getSessionManager()).getSession().getRefContext();%0A        refFactory = clientRefContext.refFactory(
 );%0A
+%0A
         
 //startF
@@ -1629,18 +1629,16 @@
         
-//
 startFXC
@@ -2064,20 +2064,27 @@
 private 
-void
+AnkorSystem
  createW
@@ -2108,32 +2108,8 @@
 tem(
-final Stage primaryStage
 ) th
@@ -2137,32 +2137,54 @@
 loymentException
+, InterruptedException
  %7B%0A        final
@@ -2679,24 +2679,85 @@
 labTest%22);%0A%0A
+        final CountDownLatch latch = new CountDownLatch(1);%0A%0A
         WebS
@@ -2903,16 +2903,17 @@
 ientId;%0A
+%0A
         
@@ -3444,26 +3444,8 @@
     
-final AnkorSystem 
 clie
@@ -3452,16 +3452,19 @@
 ntSystem
+%5B0%5D
  = syste
@@ -3508,185 +3508,64 @@
     
-RefContext clientRefContext = ((SingletonSessionManager) clientSystem.getSessionManager()).getSession().getRefContext();%0A                refFactory = clientRefContext.refFactory
+clientSystem%5B0%5D.start();%0A                latch.countDown
 ();%0A
@@ -3580,175 +3580,226 @@
     
+%7D%0A
     
-try %7B%0A                    startFXClient(primaryStage);%0A                %7D catch (IOException ignored) %7B%0A                %7D%0A            %7D%0A        %7D, URI.create(uri));
+    %7D, URI.create(uri));%0A%0A        if (latch.await(5, TimeUnit.SECONDS)) %7B%0A            return clientSystem%5B0%5D;%0A        %7D else %7B%0A            throw new IOException(%22WebSocket could not connect to %22 + uri);%0A        %7D
 %0A   

fix javafx websocket startup