package com.tomas.ckd_system;

import android.content.Context;
import android.util.Log;


import com.tomas.ckd_system.lib.WebSocketListenerAbstract;

import okhttp3.Response;
import okhttp3.WebSocket;
import okio.ByteString;

public class WsClientListener extends WebSocketListenerAbstract {
    private Context context;
    private static WsClient smartwatchClient = WsClient.getInstance();

    private WsClientListener() {}

    public WsClientListener(Context context) {
        this.context = context;
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        Log.d(context.getString(R.string.tag), "Websocket handshake");
    }
    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Log.d(context.getString(R.string.tag), "Receiving : " + text);
        smartwatchClient.messageListener.onMessage(webSocket, text);

    }
    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        Log.d(context.getString(R.string.tag),"Receiving bytes : " + bytes.hex());
    }
    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        webSocket.close(NORMAL_CLOSURE_STATUS, null);
        smartwatchClient.ws = null;
        smartwatchClient.callbackListener.onFinished("error");
        Log.d(context.getString(R.string.tag),"Closing : " + code + " / " + reason);
    }
    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        Log.e(context.getString(R.string.tag),"Error : " + t.getMessage());
        WsClient.ws = null;
        WsClient.callbackListener.onFinished("Error : "
                + (t!=null
                ? ( t.getMessage()==null || t.getMessage().equals("null") ? "The server might crash" : t.getMessage() )
                : "the server might crash"));
    }
}
