package com.ntels.kneet.v3.common.websocket;

import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.koushikdutta.async.http.WebSocket;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.util.LogUtil;
import com.ntels.kneet.v3.common.util.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 1. ClassName :   WebSocketSender
 * 2. FileName  :   WebSocketSender.java
 * 3. Package   :   com.ntels.kneet.v3.common.websocket
 * 4. Date      :   2016-06-08
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 */
public class WebSocketSender {

    private static final String TAG = WebSocketSender.class.getSimpleName();
    private WebSocket webSocket;
    private Util util;
    private Handler handler;
    private AppConfig appConfig;

    public WebSocketSender(WebSocket webSocket, Handler handler) {
        this.webSocket = webSocket;
        this.handler = handler;
        this.util = new Util();
        appConfig = AppConfig.getGlobalApplicationContext();
    }

    public void send_client_auth() {
        // TODO : 테스트 후 소스 원복
        HashMap<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put(Constants.WEBSOCKET_KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_AUTH);
        sendParams.put(Constants.WEBSOCKET_KEY_MEMBER_ID, appConfig.getLogin_Member_Id());
        sendParams.put(Constants.WEBSOCKET_KEY_AUTH_TOKEN, appConfig.getAuth_Token());
        send(util.MapToJson(sendParams));
    }

    public void send_device_register(HashMap<String, Object> hmParams) {
        send(util.MapToJson(hmParams));
    }

    public void send_device_delete(HashMap<String, Object> hmParams) {
        send(util.MapToJson(hmParams));
    }

    public void send_node_command(HashMap<String, Object> hmParams) {
        JSONObject joSendParams = null;
        JSONObject joRequestValue = new JSONObject();

        try {
            joRequestValue.put(util.null2string(hmParams.get(Constants.WEBSOCKET_KEY_CMDCLS_ID)),
                               util.null2string(hmParams.get(Constants.WEBSOCKET_KEY_CMDCLS_VALUE)));

            hmParams.remove(Constants.WEBSOCKET_KEY_CMDCLS_ID);
            hmParams.remove(Constants.WEBSOCKET_KEY_CMDCLS_VALUE);

            joSendParams = new JSONObject(util.MapToJson(hmParams));
            joSendParams.put(Constants.WEBSOCKET_KEY_REQUEST_VALUE, joRequestValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        send(joSendParams.toString());
    }

    private void send(final String sParam) {
        LogUtil.i(TAG, "send parameter : " + sParam);
        AsyncTask<String, Integer, Boolean> sendTask = new AsyncTask<String, Integer, Boolean>() {

            /**
             * Override this method to perform a computation on a background thread. The
             * specified parameters are the parameters passed to {@link #execute}
             * by the caller of this task.
             * <p/>
             * This method can call {@link #publishProgress} to publish updates
             * on the UI thread.
             *
             * @param params The parameters of the task.
             * @return A result, defined by the subclass of this task.
             * @see #onPreExecute()
             * @see #onPostExecute
             * @see #publishProgress
             */
            @Override
            protected Boolean doInBackground(String... params) {
                LogUtil.i(TAG, "doInBackground");
                LogUtil.i(TAG, "webSocket.isOpen : " + webSocket.isOpen());
                webSocket.send(sParam);
                return true;
            }

            @Override
            protected void onCancelled(Boolean aBoolean) {
                LogUtil.i(TAG, "onCancelled : " + aBoolean);
                handler.sendEmptyMessage(WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            }
        };
        new AsyncTaskCancelTimerTask(sendTask, 20000, 1000, true).start();
        sendTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
