package com.nbusy.sdk.titan.neptulon;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.ws.WebSocket;
import okhttp3.ws.WebSocketCall;
import okhttp3.ws.WebSocketListener;
import okio.Buffer;

/**
 * Neptulon connection implementation: https://github.com/neptulon/neptulon
 */
public class ConnImpl implements Conn {
    private final OkHttpClient client;
    private final Request request;
    private final WebSocketCall wsCall;
    private WebSocket ws;

    public ConnImpl() {
        client = new OkHttpClient.Builder()
                .connectTimeout(45, TimeUnit.SECONDS)
                .writeTimeout(300, TimeUnit.SECONDS)
                .readTimeout(300, TimeUnit.SECONDS)
                .build();

        request = new Request.Builder()
                .url("ws://10.0.2.2:3010")
                .build();

        wsCall = WebSocketCall.create(client, request);
    }

    public void useTLS(byte[] ca, byte[] clientCert, byte[] clientCertKey) {
        // todo: https://github.com/square/okhttp/wiki/HTTPS
    }

    public void connect() {
        // enqueue a new listener to execute the websocket call
        wsCall.enqueue(new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                ws = webSocket;
                try {
                    webSocket.sendMessage(RequestBody.create(WebSocket.TEXT, "{\"ID\": \"123\", \"Method\": \"test2\"}"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
//                throw new RuntimeException("connected!");
            }

            @Override
            public void onFailure(IOException e, Response response) {
                throw new RuntimeException(e);
            }

            @Override
            public void onMessage(ResponseBody message) throws IOException {
//                private final Gson gson = new Gson();
//                Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
//                for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
//                    System.out.println(entry.getKey());
//                    System.out.println(entry.getValue().content);
//                }
                throw new RuntimeException("got message!" + message.string());
//                message.close(); needed?
            }

            @Override
            public void onPong(Buffer payload) {
                throw new RuntimeException("got pong!");
            }

            @Override
            public void onClose(int code, String reason) {
                throw new RuntimeException("closed!");
            }
            // ...
        });
    }

    public void close() throws IOException {
        wsCall.cancel();
        ws.close(0, "");
    }
}

@@ -97,16 +97,49 @@
 imeUnit;
+%0Aimport java.util.logging.Logger;
 %0A%0Aimport
@@ -507,24 +507,115 @@
 ents Conn %7B%0A
+    private static final Logger logger = Logger.getLogger(ConnImpl.class.getSimpleName());%0A
     private 
@@ -1364,20 +1364,16 @@
 queue a 
-new 
 listener
@@ -1380,34 +1380,41 @@
  to 
-execu
+initia
 te the 
-webs
+WebS
 ocket c
-all
+onnection
 %0A   
@@ -1606,294 +1606,31 @@
     
-try %7B%0A                    webSocket.sendMessage(RequestBody.create(WebSocket.TEXT, %22%7B%5C%22ID%5C%22: %5C%22123%5C%22, %5C%22Method%5C%22: %5C%22test2%5C%22%7D%22));%0A                %7D catch (IOException e) %7B%0A                    throw new RuntimeException(e);%0A                %7D%0A//                throw new RuntimeException(%22
+logger.info(%22WebSocket 
 conn
@@ -1634,17 +1634,17 @@
 onnected
-!
+.
 %22);%0A    
@@ -1766,36 +1766,82 @@
     
-throw new RuntimeException(e
+logger.warning(%22WebSocket connection closed with error: %22 + e.getMessage()
 );%0A 
@@ -2538,65 +2538,8 @@
 ) %7B%0A
-                throw new RuntimeException(%22got pong!%22);%0A
     
@@ -2650,43 +2650,38 @@
     
-throw new RuntimeException(%22
+logger.info(%22WebSocket 
 closed
-!
+.
 %22);%0A
@@ -2706,28 +2706,164 @@
     
-    // ...%0A        %7D
+%7D);%0A    %7D%0A%0A    public void send() throws IOException %7B%0A        ws.sendMessage(RequestBody.create(WebSocket.TEXT, %22%7B%5C%22ID%5C%22: %5C%22123%5C%22, %5C%22Method%5C%22: %5C%22test2%5C%22%7D%22)
 );%0A 

add basic logging to websocket connection