/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.onecable.admin.view.things;


import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.AppConfig;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.c_interface.ListInterface;
import com.ntels.onecable.admin.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.LogUtil;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.ntels.onecable.admin.view.dialog.DialogCustomList;

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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;

import static com.ntels.onecable.admin.common.Constants.EXTRA_ERROR_CODE;
import static com.ntels.onecable.admin.common.Constants.EXTRA_RESULT_STATE;


/**
 * <pre>
 * 1. ClassName :   ThingsDetail
 * 2. FileName  :   ThingsDetail.java
 * 3. Package   :   com.ntels.onecable.view.things
 * 4. Date      :   2016-11-25
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class ThingsDetail extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult,
        ListInterface {

    private static final String TAG = ThingsDetail.class.getSimpleName();

    private static final int MSG_COM_G_DEVICES_DEVICE_ID = 1;
    private static final int MSG_COM_WS_NODE_COMMAND = 2;
    private static final int MSG_COM_WS_NODE_PROFILE_UPDATE = 3;
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private String mDeviceId = "";
    private String mDeviceTypeId = "";
    private String mNodeId = "";
    private boolean mIsReloadFinish = false;
    /*툴바 관련*/
//    private Toolbar mToolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<>();
    private int mType = 0;
    /*리스트 관련*/
    private ThingsDetailAdapter mDataAdapter;
    private RecyclerView mRcvList;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private GridLayoutManager mGlmList;
    private LinearLayoutManager llmList;
    private DialogCustomList.Builder dialogListBuilder;
    private boolean mIsListEdit = false;
    private boolean mIsLoading = false;
    private boolean mIsListHeader = false;
    private boolean mIsListFooter = false;
    private boolean mIsListFooterVisible = false;
    private int mListColumnsCnt = 1;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mRequestValue = "";
    private String mCmdClsId = "";
    private String mDeviceName = "";
    private String mCommandId = "";
    private int mThingsAction = 0;
    private int mImageIndex = 0;
    private ImageView[] mImageViews = new ImageView[50];
    //    private WebSocketService webSocketService;
    private boolean mIsBound = false;
    private int mOptionCount = 0;
    /**
     * 노드 제어 타임아웃 체크 리스너.
     */
    private     Handler loadingHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int row = msg.what;
            if (!mIsLoading) {
                if (row >= 0) {
                    Object requestTime = mTotalList.get(row).get(Constants.KEY_REQUEST_TIME);
                    if (requestTime != null && !requestTime.toString().isEmpty()) {
                        mTotalList.get(row).put(Constants.KEY_REQUEST_TIME, "");
                        dispListChanged();
                    }

                }
            }
        }
    };

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                Dlog.i(TAG, "websocket message mType : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if (jsonObject.has(Constants.KEY_RESULT_CODE)) {
                    resultCode = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_CODE));
                }
                if (jsonObject.has(Constants.KEY_RESULT_MSG)) {
                    resultMsg = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_MSG));
                }
                if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_COMMAND)) {
                    resultWsNodeCommand(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_COMMAND_RESULT)) {
                    notificationWsNodeCommandResult(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_CONTENT)) {
                    notificationWsNodeContent(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_PROFILE_UPDATE)) {
                    resultWsNodeProfileUpdateCommand(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_PROFILE_UPDATE_RESULT)) {
                    notificationWsNodeProfileUpdateResult(jsonObject);
                } else {
                    /*final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });*/
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {

            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {
                case Constants.WEBSOCKET_ERROR_TIMEOUT:
                    Dlog.i(TAG, "WEBSOCKET_ERROR_TIMEOUT!!!");
                    for (HashMap<String, Object> hm : mTotalList) {
                        hm.put(Constants.KEY_REQUEST_TIME, "");
                    }
                    break;
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    Dlog.i(TAG, "WEBSOCKET_ERROR_NOT_CONNECTED!!!");
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                    break;
                default:
                    break;
            }
            dispListChanged();
        }
    }

    ;

    @Override
    public void onStop() {

        super.onStop();
        Dlog.v("onStop()");
    }

    @Override
    public void onPause() {

        super.onPause();
        Dlog.v("onPause()");
    }

    @Override
    public void onResume() {

        super.onResume();
        Dlog.v("onResume()");
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Dlog.v("onDestroy()");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = ThingsDetail.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        setIsWebSocket(true);

        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.things_detail, null);
        this.setContentView(viewToLoad);

        Intent intent = getIntent();
        mDeviceId = intent.getStringExtra(Constants.EXTRA_DEVICE_ID);
        mDeviceTypeId = intent.getStringExtra(Constants.EXTRA_DEVICE_TYPE_ID);
        mNodeId = intent.getStringExtra(Constants.EXTRA_NODE_ID);


        displayListView();
    }


    /**
     * UI display.
     */
    private void displayListView() {


        if (mDeviceTypeId.equals(Constants.DEVICE_TYPE_ID_GASVALVE_CLOSEONLY)) {
            mUtil.getTextView(mActivity, R.id.tvTitle).setText(mUtil.getString(mActivity, R.string.layout_things_device_add_02));
        } else if (mDeviceTypeId.equals(Constants.DEVICE_TYPE_ID_SMARTPLUG)) {
            mUtil.getTextView(mActivity, R.id.tvTitle).setText(mUtil.getString(mActivity, R.string.layout_things_device_add_06));
        } else if (mDeviceTypeId.equals(Constants.DEVICE_TYPE_ID_DOORSENSOR)) {
            mUtil.getTextView(mActivity, R.id.tvTitle).setText(mUtil.getString(mActivity, R.string.layout_things_device_add_12));
        }
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnRefresh).setOnClickListener(this);

        mTotalList.clear();

        mSwipeRefreshLayout = (SwipeRefreshLayout)  findViewById(R.id.swiperefreshlayou);
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light,
                android.R.color.holo_green_light, android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {

                if (!mDataAdapter.getListCheck()) {
                    if (!mIsLoading) {
                        onListReload();
//                        if (!mCallback.getWebSocketService().isWebSocketConnected()) {
//                            mCallback.getWebSocketService().webSocketConnect();
//                        }
                    }
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        mIsListFooter = false;
        mIsListHeader = true;
        mIsListFooterVisible = false;
        mDataAdapter = new ThingsDetailAdapter(mActivity, R.layout.row_things_detail_head, R.layout.row_things_detail_list, R.layout.row_footer_things_list
                , mTotalList, this);
        mDataAdapter.setFooterCheck(mIsListFooter);
        mDataAdapter.setHeaderCheck(mIsListHeader);
        mDataAdapter.setFooterVisible(mIsListFooterVisible);

        mRcvList = (RecyclerView) findViewById(R.id.rcvList);
        mRcvList.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent event) {

                Dlog.i(TAG, "mRcvList onTouch!!");
                if (mSwipeRefreshLayout.isRefreshing()) {
                    return true;
                }
                return false;
            }
        });
        mRcvList.setHasFixedSize(true);
        mListColumnsCnt = 1;
        if (mListColumnsCnt == 1) {
            llmList = new LinearLayoutManager(mActivity);
            mRcvList.setLayoutManager(llmList);
        } else {
            mGlmList = new GridLayoutManager(mActivity, mListColumnsCnt, GridLayoutManager.VERTICAL, false);
            mGlmList.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

                @Override
                public int getSpanSize(int position) {

                    int positionType = mDataAdapter.getItemViewType(position);
                    int totalConut = mDataAdapter.getItemCount();
                    int valueConut = mDataAdapter.getItemCount();
                    if (mIsListHeader) {
                        valueConut = totalConut - 1;
                    }

                    if (positionType == mDataAdapter.TYPE_HEADER) {
                        return mGlmList.getSpanCount();
                    } else {
                        return 1;
//                        return mDataAdapter.getItemViewType(position) == 1 ? 1 : (valueConut % mListColumnsCnt == 1 ? mGlmList
// .getSpanCount
//                                () : 1);
                    }
                }
            });
            mRcvList.setLayoutManager(mGlmList);
        }
//        mRcvList.addItemDecoration(new DividerItemDecoration(getActivity(), R.drawable.color_line_01));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(mDataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        mRcvList.setAdapter(scaleAdapter);


        if (!mIsLoading) {
            onListReload();
        }
    }

    private void dispListChanged() {

        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
        mDataAdapter.notifyDataSetChanged();
    }

    /**
     * mSwipeRefreshLayout enable/disable.
     *
     * @param isRefresh true : enable, false : disable
     */
    private void setRefresh(boolean isRefresh) {

        if (isRefresh) {
            mSwipeRefreshLayout.setEnabled(true);
        } else {
            mSwipeRefreshLayout.setEnabled(false);
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                break;
            case R.id.btnRefresh:
                onListReload();
                break;
            default:
                break;
        }
    }

    /**
     * 장치 상세조회(해당 장치의 상세 정보를 조회한다. (장치가 보유한 모든 커맨드 클래스 리스트를 보여준다)) 요청.
     */
    private void sendGetDevicesDetail() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity, !mSwipeRefreshLayout.isRefreshing());

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetDevicesDetail(result);
                }
            });
            mTotalList.clear();
            mSwipeRefreshLayout.setVisibility(View.GONE);
            httpSend.getNodeDetail(mDeviceId, mNodeId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 장치 상세 조회(해당 장치의 상세 정보를 조회한다. (장치가 보유한 모든 커맨드 클래스 리스트를 보여준다)) 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultGetDevicesDetail(Response response) {

        mIsLoading = false;
        try {
            if (response.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
                String deviceName = "";
                String deviceclassTypeId = "";
                String onlineState = "";
                String nodeId = "";

                if (joResult.has(Constants.KEY_NODE_ID)) {
                    nodeId = mUtil.null2string(joResult.get(Constants.KEY_NODE_ID));
                }
                if (joResult.has(Constants.KEY_DEVICECLASS_TYPE_ID)) {
                    deviceclassTypeId = mUtil.null2string(joResult.get(Constants.KEY_DEVICECLASS_TYPE_ID));
                }
                if (joResult.has(Constants.KEY_ONLINE_STATE)) {
                    onlineState = mUtil.null2string(joResult.get(Constants.KEY_ONLINE_STATE));
                }

                String profileUpdateYn = mUtil.null2string(joResult.get(Constants.KEY_PROFILE_UPDATE_YN));
                if (profileUpdateYn.equals("Y")) {
                    mUtil.getView(mActivity, R.id.llUpdate).setVisibility(View.VISIBLE);
                } else {
                    mUtil.getView(mActivity, R.id.llUpdate).setVisibility(View.GONE);
                }
//                String deviceclassTypeId = mUtil.null2string(joResult.get(Constants.KEY_DEVICECLASS_TYPE_ID));
//                mUtil.getImageView(mActivity, R.id.ivThingsIcon).setImageResource(
//                        mUtil.getImageId(mActivity, "img_" + deviceclassTypeId + "_rule"));

                // 장치명
                String prdName = mUtil.null2string(joResult.get(Constants.KEY_PRD_NAME));
                String prdUserName = mUtil.null2string(joResult.get(Constants.KEY_PRD_USER_NAME));
                deviceName = !prdUserName.equals("") ? prdUserName : prdName;
                mDeviceName = deviceName;
//                mUtil.getTextView(mActivity, R.id.tvNodeId).setText(mUtil.getString(mActivity, R.string.layout_things_detail_04) + nodeId);


                HashMap<String, Object> hmTempNode = new HashMap<String, Object>();
                hmTempNode.put(Constants.KEY_DEVICE_ID, deviceId);
                hmTempNode.put(Constants.KEY_NODE_ID, nodeId);
                hmTempNode.put(Constants.KEY_NODE_NAME, mDeviceName);
                mTotalList.add(hmTempNode);

                String cmdclsList = mUtil.null2string(joResult.get(Constants.KEY_CMDCLS_LIST));
                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(cmdclsList);
                Dlog.i(TAG, "alList : " + alList.toString());
                if (alList.size() > 0) {
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp = alList.get(row);
                        hmTemp.put(Constants.KEY_DEVICE_ID, deviceId);
                        hmTemp.put(Constants.KEY_NODE_ID, nodeId);
                        hmTemp.put(Constants.KEY_DEVICECLASS_TYPE_ID, deviceclassTypeId);
                        hmTemp.put(Constants.KEY_ONLINE_STATE, onlineState);
                        hmTemp.put(Constants.KEY_DEVICE_NAME, deviceName);
                        Dlog.i(TAG, "hmTemp : " + hmTemp.toString());
                        mTotalList.add(hmTemp);
                    }
                }
                dispListChanged();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if (resultCode.equals("401")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        } finally {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), 10);
                }
                break;
            case Constants.MSG995:
                if (btnResult == 1) {
                    dialog_show();
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_WS_NODE_PROFILE_UPDATE), 10);
                }
                break;
            case Constants.MSG932:
                break;
            case Constants.MSG933:
                break;
            default:
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mIntent.putExtra(Constants.EXTRA_RELOAD_FLAG, mIsReloadFinish);
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_THINGS_NAME_CHANGE:
                    mIsReloadFinish = true;
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
                    break;
                case Constants.ACT_THINGS_DEVICE_DEL_STEP0:
                case Constants.ACT_THINGS_DEVICE_DEL_OFF_STEP1:
                    mIsReloadFinish = true;
                    onBackPressed();
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                mActivity.setResult(RESULT_CANCELED, new Intent());
                finish();
            }
        }
    }


    @Override
    public void onListReload() {
        mIsLoading = true;
//        if (setHomeHubStateList()) {
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
        // do something
    }

    @Override
    public void onLogout() {
        //        mCallback.onLogout();
    }

    private String callHttpDeviceId = "";
    private String callHttpNodeId = "";
    private String callHttpRequestValue = "";
    private String callHttpCmdclsId = "";
    @Override
    public void onCallAction(int callType, int position) {

        switch (callType) {
            case 3:
                // 실행하기
                mRequestValue = mDataAdapter.getHttpValue();
                mCmdClsId = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_ID));
                String cmdclsCode = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_CODE));

                mUtil.callBtnGoogleAnalytics(mActivity, "Control_Things", cmdclsCode + "_2depth");

                LogUtil.i(TAG, "Row info : " + mTotalList.get(position).toString());
                Dlog.v("mRequestValue", mRequestValue);
                String contentValue = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CONTENT_VALUE));
                Dlog.v("contentValue", contentValue);
                Dlog.v("KEY_cmdcls_id", mCmdClsId);
                String cmdclsTypeId = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_TYPE_ID));
                String tempValue = mUtil.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_" + mRequestValue);

                if (mRequestValue.equals(contentValue)) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG899).replaceAll("\\'컨텐츠밸류\\'", tempValue), Toast
                            .LENGTH_SHORT);
                    dispListChanged();
                    return;
                } else {
                    mUtil.setVibrator(100);
                }

                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_WS_NODE_COMMAND, position, 0), 10);
                break;
            default:
                break;
        }

    }

    /**
     * 서비스 허브에 노드 제어를 요청한다.
     */
    private void sendWsNodeCommand(int position) {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_NODE_COMMAND);
        sendParams.put(Constants.KEY_DEVICE_ID, mDeviceId);
        sendParams.put(Constants.KEY_NODE_ID, mNodeId);
        String requestId = mAppConfig.getSelectServicehubRequestId();
        sendParams.put(Constants.KEY_REQUEST_ID, requestId);
        sendParams.put(Constants.KEY_COMMAND_TYPE, Constants.WEBSOCKET_COMM_TYPE_CONTROL);
        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
        sendParams.put(Constants.KEY_CMDCLS_ID, mCmdClsId);
        sendParams.put(Constants.KEY_CMDCLS_VALUE, mRequestValue);

        getWebSocketService().send(Constants.WEBSOCKET_SEND_NODE_COMMAND, sendParams);

        // 제어 요청 10초 후까지 응답이 없으면 타임아웃 처리.
        mTotalList.get(position).put(Constants.KEY_REQUEST_TIME, mUtil.getUtcTime());
        mTotalList.get(position).put(Constants.KEY_REQUEST_ID, requestId);
        loadingHandler.sendEmptyMessageDelayed(position, 10000);
    }

    /**
     * 서비스 허브에 노드제어 요청 결과 수신.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    private void resultWsNodeCommand(JSONObject joResult) throws JSONException {
        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        if (resultCode.equals("00")) {
            String resultDeviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
            String resultNodeId = mUtil.null2string(joResult.get(Constants.KEY_NODE_ID));
            String resultRequestTime = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_TIME));
            String resultCommandId = mUtil.null2string(joResult.get(Constants.KEY_COMMAND_ID));
            String resultRequestId = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_ID));
            int loadingRow = -1;
            for (int row = 0; row < mTotalList.size(); row++) {
                String deviceId = mUtil.null2string(mTotalList.get(row).get(Constants.KEY_DEVICE_ID));
                String nodeId = mUtil.null2string(mTotalList.get(row).get(Constants.KEY_NODE_ID));
                String requestId = mUtil.null2string(mTotalList.get(row).get(Constants.KEY_REQUEST_ID));
                if (resultDeviceId.equals(deviceId) && resultNodeId.equals(nodeId) && resultRequestId.equals(requestId)) {
                    mTotalList.get(row).put(Constants.KEY_REQUEST_TIME, resultRequestTime);
                    mTotalList.get(row).put(Constants.KEY_REQUEST_ID, resultCommandId);
                    loadingRow = row;
                    Dlog.v(TAG, "resultRequestTime =" + resultRequestTime);
                    break;
                }
            }
            // 제어 요청 10초 후까지 응답이 없으면 타임아웃 처리.
            if (loadingRow >= 0) {
                loadingHandler.removeMessages(loadingRow);
                loadingHandler.sendEmptyMessageDelayed(loadingRow, 10000);
            }
        } else {
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
        }
        dispListChanged();
    }

    /**
     * 서비스 허브에 노드 프로파일 업데이트를 요청한다.
     */
    private void sendWsNodeProfileUpdateCommand() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_NODE_PROFILE_UPDATE);
        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
        sendParams.put(Constants.KEY_DEVICE_ID, mDeviceId);
        sendParams.put(Constants.KEY_NODE_ID, mNodeId);
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());

        getWebSocketService().send(Constants.WEBSOCKET_SEND_NODE_PROFILE_UPDATE, sendParams);
    }

    /**
     * {@link ThingsDetail#sendWsNodeProfileUpdateCommand() 노드 제어} 요청 결과.
     *
     * @param joResult 결과 json object
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsNodeProfileUpdateCommand(JSONObject joResult) throws JSONException {

        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        if (resultCode.equals("00")) {
            mCommandId = joResult.getString(Constants.KEY_COMMAND_ID);
        } else {
//            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
//            mCustomDialog.msgAlert(mActivity, Constants.MSG933);
            Dlog.v(joResult.toString());
            String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

            if ("401".equals(resultCode)) {
                mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
            } else if ("401-106".equals(resultCode)) {
                mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
            } else {
                mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
            }
        }
    }

    /**
     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 결과를 푸쉬받는다.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    private void notificationWsNodeProfileUpdateResult(JSONObject joResult) throws JSONException {
        try {

            dialog_dismiss();
            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
            if (resultCode.equals("00")) {
                mUtil.getView(mActivity, R.id.llUpdate).setVisibility(View.INVISIBLE);
                mCustomDialog.msgAlert(mActivity, Constants.MSG932);
            } else {
                Dlog.v(joResult.toString());
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if ("401".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if ("401-106".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        try {
            mUtil.getView(mActivity, R.id.llBtn2).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 서비스 허브에서 노드 제어 처리 후 결과를 푸쉬받는다.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    private void notificationWsNodeCommandResult(JSONObject joResult) throws JSONException {
        String resultDeviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        String resultNodeId = mUtil.null2string(joResult.get(Constants.KEY_NODE_ID));
        String resultRequestTime = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_TIME));
        String resultCommandId = mUtil.null2string(joResult.get(Constants.KEY_COMMAND_ID));
//        String resultRequestId = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_ID));
        int loadingRow = -1;
        for (int row = 0; row < mTotalList.size(); row++) {

            String deviceId = mUtil.null2string(mTotalList.get(row).get(Constants.KEY_DEVICE_ID));
            String nodeId = mUtil.null2string(mTotalList.get(row).get(Constants.KEY_NODE_ID));
            String requestId = mUtil.null2string(mTotalList.get(row).get(Constants.KEY_REQUEST_ID));
            if (resultDeviceId.equals(deviceId) && resultNodeId.equals(nodeId) && resultCommandId.equals(requestId) ) {
                mTotalList.get(row).put(Constants.KEY_REQUEST_TIME, "");
                mTotalList.get(row).put(Constants.KEY_REQUEST_ID, "");

                Dlog.v(TAG, "resultRequestTime =" + resultRequestTime);
                Dlog.v(TAG, "resultRequestTime =" + resultRequestTime);
                loadingRow = row;
                break;
            }
        }
        if (loadingRow >= 0) {
            loadingHandler.removeMessages(loadingRow);
        }
        dispListChanged();

    }

    /**
     * 서비스허브에서 노드 컨텐트 정보를 푸쉬받는다.
     *
     * @param joResult 노드 컨텐트 json object
     *
     * @exception JSONException json parsing exception
     */
    private void notificationWsNodeContent(JSONObject joResult) throws JSONException {
        Dlog.i(TAG, "notificationWsNodeContent!!");
        String tempDeviceId1 = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        String tempNodeId1 = mUtil.null2string(joResult.get(Constants.KEY_NODE_ID));
        String tempCollectTime1 = mUtil.null2string(joResult.get(Constants.KEY_COLLECT_TIME));
        HashMap<String, Object> hmContentValue = mUtil.jsonToMap(joResult.get(Constants.KEY_CONTENT_VALUE));
        String tempOnlineState1 = mUtil.null2string(hmContentValue.get(Constants.KEY_ONLINE));

        for (int row1 = 0; row1 < mTotalList.size(); row1++) {
            String tempDeviceId2 = mUtil.null2string(mTotalList.get(row1).get(Constants.KEY_DEVICE_ID));
            String tempNodeId2 = mUtil.null2string(mTotalList.get(row1).get(Constants.KEY_NODE_ID));
            if (!tempDeviceId1.equals(tempDeviceId2) || !tempNodeId1.equals(tempNodeId2)) {
                return;
            }
            String contentValue = mUtil.null2string(hmContentValue.get(mTotalList.get(row1).get(Constants.KEY_CMDCLS_ID)));
            Dlog.i(TAG, "cmdcls_id : " + mUtil.null2string(mTotalList.get(row1).get(Constants.KEY_CMDCLS_ID)));
            Dlog.i(TAG, "contentValue : " + contentValue);
            if (!contentValue.isEmpty()) {
                mTotalList.get(row1).put(Constants.KEY_CONTENT_VALUE, contentValue);
                mTotalList.get(row1).put(Constants.KEY_COLLECT_TIME, tempCollectTime1);
                mTotalList.get(row1).put(Constants.KEY_CONTENT_LAST_DATETIME, tempCollectTime1);
            }
            if (!tempOnlineState1.isEmpty()) {
                mTotalList.get(row1).put(Constants.KEY_ONLINE_STATE, tempOnlineState1);
            }
            Dlog.i(TAG, "mTotalList : " + mTotalList.toString());
        }
        dispListChanged();
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICES_DEVICE_ID:
                    sendGetDevicesDetail();
                    break;
                case MSG_COM_WS_NODE_COMMAND:
                    sendWsNodeCommand(msg.arg1);
                    break;
                case MSG_COM_WS_NODE_PROFILE_UPDATE:
                    sendWsNodeProfileUpdateCommand();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}