package com.github.nkzawa.engineio.client.transports;


import com.github.nkzawa.engineio.client.Transport;
import com.github.nkzawa.engineio.parser.Packet;
import com.github.nkzawa.engineio.parser.Parser;
import com.github.nkzawa.parseqs.ParseQS;
import com.github.nkzawa.thread.EventThread;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ws.WebSocket.PayloadType;
import com.squareup.okhttp.ws.WebSocketCall;
import com.squareup.okhttp.ws.WebSocketListener;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.net.ssl.SSLSocketFactory;

import okio.Buffer;
import okio.BufferedSource;

import static com.squareup.okhttp.ws.WebSocket.PayloadType.BINARY;
import static com.squareup.okhttp.ws.WebSocket.PayloadType.TEXT;

public class WebSocket extends Transport {

    public static final String NAME = "websocket";
    private com.squareup.okhttp.ws.WebSocket ws;

    public WebSocket(Options opts) {
        super(opts);
        this.name = NAME;
    }

    protected void doOpen() {
        if (!this.check()) {
            return;
        }

        Map<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
        this.emit(EVENT_REQUEST_HEADERS, headers);

        final WebSocket self = this;
        final OkHttpClient client = new OkHttpClient();
        if (this.sslContext != null) {
            SSLSocketFactory factory = sslContext.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();
            client.setSslSocketFactory(factory);
        }
        final Request request = new Request.Builder()
                .url(uri())
                .build();
        WebSocketCall.create(client, request).enqueue(new WebSocketListener() {
            @Override
            public void onOpen(com.squareup.okhttp.ws.WebSocket webSocket, Request request, Response response) throws IOException {
                ws = webSocket;
                final Map<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
                for (int i = 0, size = response.headers().size(); i < size; i++) {
                    headers.put(response.headers().name(i), response.headers().value(i));
                }
                EventThread.exec(new Runnable() {
                    @Override
                    public void run() {
                        self.emit(EVENT_RESPONSE_HEADERS, headers);
                        self.onOpen();
                    }
                });
            }

            @Override
            public void onMessage(BufferedSource payload, PayloadType type) throws IOException {
                Object data;
                switch (type) {
                    case TEXT:
                        data = payload.readUtf8();
                        break;
                    case BINARY:
                        data = payload.readByteArray();
                        break;
                    default:
                        throw new IllegalStateException("Unknown payload type: " + type);
                }
                payload.close();
                final Object finalData = data;
                EventThread.exec(new Runnable() {
                    @Override
                    public void run() {
                        if (finalData == null) {
                            return;
                        }
                        if (finalData instanceof String) {
                            self.onData((String) finalData);
                        } else {
                            self.onData((byte[]) finalData);
                        }
                    }
                });

            }

            @Override
            public void onPong(Buffer payload) {
            }

            @Override
            public void onClose(int code, String reason) {
                EventThread.exec(new Runnable() {
                    @Override
                    public void run() {
                        self.onClose();
                    }
                });
            }

            @Override
            public void onFailure(final IOException e) {
                EventThread.exec(new Runnable() {
                    @Override
                    public void run() {
                        self.onError("websocket error", e);
                    }
                });
            }
        });
        client.getDispatcher().getExecutorService().shutdown();
    }

    protected void write(Packet[] packets) {
        final WebSocket self = this;
        this.writable = false;
        for (Packet packet : packets) {
            Parser.encodePacket(packet, new Parser.EncodeCallback() {
                @Override
                public void call(Object packet) {
                    try {
                        if (packet instanceof String) {
                            self.ws.sendMessage(TEXT, new Buffer().writeUtf8((String) packet));
                        } else if (packet instanceof byte[]) {
                            self.ws.sendMessage(BINARY, new Buffer().write((byte[]) packet));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        final Runnable ondrain = new Runnable() {
            @Override
            public void run() {
                self.writable = true;
                self.emit(EVENT_DRAIN);
            }
        };

        // fake drain
        // defer to next tick to allow Socket to clear writeBuffer
        EventThread.nextTick(ondrain);
    }

    @Override
    protected void onClose() {
        super.onClose();
    }

    protected void doClose() {
        if (this.ws != null) {
            try {
                this.ws.close(1000, "");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    protected String uri() {
        Map<String, String> query = this.query;
        if (query == null) {
            query = new HashMap<String, String>();
        }
        String schema = this.secure ? "wss" : "ws";
        String port = "";

        if (this.port > 0 && (("wss".equals(schema) && this.port != 443)
                || ("ws".equals(schema) && this.port != 80))) {
            port = ":" + this.port;
        }

        if (this.timestampRequests) {
            query.put(this.timestampParam, String.valueOf(new Date().getTime()));
        }

        String _query = ParseQS.encode(query);
        if (_query.length() > 0) {
            _query = "?" + _query;
        }

        return schema + "://" + this.hostname + port + this.path + _query;
    }

    private boolean check() {
        // for checking if the websocket is available. Should we remove?
        return true;
    }

}
@@ -286,16 +286,52 @@
 Thread;%0A
+import com.squareup.okhttp.Headers;%0A
 import c
@@ -363,16 +363,16 @@
 Client;%0A
-
 import c
@@ -2199,32 +2199,94 @@
 NSITIVE_ORDER);%0A
+                Headers responseHeaders = response.headers();%0A
                 
@@ -2316,26 +2316,23 @@
 response
-.h
+H
 eaders
-()
 .size();
@@ -2389,26 +2389,23 @@
 response
-.h
+H
 eaders
-()
 .name(i)
@@ -2414,26 +2414,23 @@
 response
-.h
+H
 eaders
-()
 .value(i
@@ -2814,16 +2814,22 @@
 payload,
+ final
  Payload
@@ -2883,24 +2883,31 @@
  Object data
+ = null
 ;%0A          
@@ -3218,71 +3218,291 @@
     
-throw new IllegalStateException(%22Unknown payload type: %22 + type
+EventThread.exec(new Runnable() %7B%0A                            @Override%0A                            public void run() %7B%0A                                self.onError(%22Unknown payload type: %22 + type, new IllegalStateException());%0A                            %7D%0A                        %7D
 );%0A 
@@ -5639,34 +5639,49 @@
         
-e.printStackTrace(
+self.onError(%22websocket error%22, e
 );%0A     
@@ -6341,26 +6341,34 @@
     
-e.printStackTrace(
+onError(%22doClose error%22, e
 );%0A 

handle error using onError