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

package com.ntels.onecable.view.things;

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

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

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

/**
 * <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 CustomActionBarActivity 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;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private String mDeviceId = "";
    private String mNodeId = "";
    private boolean mIsReloadFinish = false;
    /*툴바 관련*/
    private Toolbar mToolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> mMandatoryTotalList = new ArrayList<>();
    private int mType = 0;
    /*리스트 관련*/
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private DialogCustomList.Builder mDialogListBuilder;
    private boolean mIsLoading = false;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent intent;
    private Util util = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private String requestValue = "";
    private String cmdclsId = "";
    private int thingsAction = 0;
    private int imageIndex = 0;
    private CustomViewPager nodeMandatoryPager;
    private ThingsDetailVpAdapter pageAdapter;
    private ImageView[] imageViews = new ImageView[50];
    private WebSocketService webSocketService;
    private boolean isBound = false;
    private int optionCount = 0;
    /** 노드 제어 타임아웃 체크 리스너. */
    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, "");
                        setNodeDisp();
                        setHomeHubStateList();
                    }

                }
            }
        }
    };
    private OnWebSocketResponse webSocketResponse = new OnWebSocketResponse() {
        @Override
        public void onResponse(String result) {
            try {

                JSONObject jsonObject = new JSONObject(result);
                String messageType = util.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                LogUtil.i(TAG, "websocket message mType : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if (jsonObject.has(Constants.KEY_RESULT_CODE)) {
                    resultCode = util.null2string(jsonObject.get(Constants.KEY_RESULT_CODE));
                }
                if (jsonObject.has(Constants.KEY_RESULT_MSG)) {
                    resultMsg = util.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 {
                    /*final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            util.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });*/
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public void onError(int code, String message) {
            switch (code) {
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    customDialog.msgAlert(mActivity, Constants.MSG807);
                    break;
                default:
                    break;
            }
            setNodeDisp();
            setHomeHubStateList();
        }
    };
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtil.i(TAG, "onServiceConnected!!");
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            webSocketService = binder.getService();
            webSocketService.addWebSocketResponse(webSocketResponse);
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    @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()");
        if (isBound) {
            webSocketService.removeWebSocketResponse(webSocketResponse);
            unbindService(serviceConnection);
            isBound = false;
        }
    }

    @Override
    protected void onNewIntent(Intent saveIntent) {

        super.onNewIntent(saveIntent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        Intent serviceIntent = new Intent(mActivity, WebSocketService.class);
        mActivity.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

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

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

        setToolbar();

        displayListView();
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        mToolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        util.setKeyboardHide(mActivity, mToolbar);
        util.getTextView(mToolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        util.getTextView(mToolbar, R.id.tvToolbarTitle2).setVisibility(View.VISIBLE);
        util.getTextView(mToolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        util.getTextView(mToolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        util.getTextView(mToolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        util.getTextView(mToolbar, R.id.btnToolbarDel).setVisibility(View.GONE);
        util.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        util.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);

        util.getTextView(mToolbar, R.id.tvToolbarTitle1).setText(util.getString(mActivity, R.string.layout_things_detail_01));
        util.getTextView(mToolbar, R.id.tvToolbarTitle2).setText("");

        util.getView(mToolbar, R.id.btnToolbarMore).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ArrayList<HashMap<String, Object>> alMenuList = new ArrayList<HashMap<String, Object>>();
                alMenuList.add(util.getPopMenu(6));

                if (mAppConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    alMenuList.add(util.getPopMenu(2));
                }
                msgAlertList(alMenuList);
            }
        });
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 타이틀과 리스트를 보여준다.
     */
    public void setHomeHubStateAll() {

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 다른 타이틀을 보여준다.
     */
    public void setHomeHubStateTitle() {

        if (mAppConfig.getCtrtGroupId().equals("")) {
            //홈그룹 없을경우
            util.getView(mToolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
            util.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
            util.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
            util.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
            if (mDialogListBuilder != null) {
                mDialogListBuilder.create().dismiss();
            }
        } else {
            //홈그룹 있을경우
            if (mAppConfig.getSelect_Homegrp_Homehub_Device_Id().equals("")) {
                //홈그룹은 있고 홈허브가 없는경우
                util.getView(mToolbar, R.id.llToolbar).setVisibility(View.GONE);
                util.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.VISIBLE);
                util.getTextView(mToolbar, R.id.tvToolbarHomeHub).setText(util.getString(mActivity, R.string.layout_homehub_delete));
                util.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                util.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                if (mDialogListBuilder != null) {
                    mDialogListBuilder.create().dismiss();
                }
            } else {
                if (mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                    //홈그룹은 있고 홈허브가 오프라인인경우
                    util.getView(mToolbar, R.id.llToolbar).setVisibility(View.GONE);
                    util.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.VISIBLE);
                    util.getTextView(mToolbar, R.id.tvToolbarHomeHub).setText(util.getString(mActivity, R.string.layout_homehub_offline));
                } else {
                    //홈그룹은 있고 홈허브가 온라인인 경우
                    util.getView(mToolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
                    util.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 다른 리스트를 보여준다.
     *
     * @return 리스트 갱신했는지 여부
     */
    public boolean setHomeHubStateList() {

        Boolean isListLoad = false;
        if (mAppConfig.getCtrtGroupId().equals("")) {
            //홈그룹 없을경우
            mSwipeRefreshLayout.setVisibility(View.INVISIBLE);
            callVpReLoad();
            setRefresh(false);
        } else {
            //홈그룹 있을경우
            if (mAppConfig.getSelect_Homegrp_Homehub_Device_Id().equals("")) {
                //홈그룹은 있고 홈허브가 없는경우
                if (mAppConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    mSwipeRefreshLayout.setVisibility(View.INVISIBLE);
                    callVpReLoad();
                    setRefresh(false);
                } else {
                    mSwipeRefreshLayout.setVisibility(View.INVISIBLE);
                    callVpReLoad();
                    setRefresh(false);
                }
            } else {
                if (mTotalList.size() > 0) {
                    mSwipeRefreshLayout.setVisibility(View.VISIBLE);
                } else {
                    mSwipeRefreshLayout.setVisibility(View.INVISIBLE);
                }
                callVpReLoad();
                isListLoad = true;
            }
        }
        return isListLoad;
    }

    /**
     * view pager reload.
     */
    private void callVpReLoad() {

        if (mMandatoryTotalList.size() > 0) {
            if (optionCount == 0) {
                pageAdapter.setHideDivider(false);
            } else {
                pageAdapter.setHideDivider(true);
            }
            nodeMandatoryPager.getAdapter().notifyDataSetChanged();
            util.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).setVisibility(View.GONE);

            nodeMandatoryPager.post(new Runnable() {
                @Override
                public void run() {

                    try {
                        if (mMandatoryTotalList.size() > 1) {
                            util.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).setVisibility(View.VISIBLE);

                            ViewGroup.LayoutParams params1 = util.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).getLayoutParams();
                            params1.height = util.getView(mActivity, R.id.vpNode_M).getHeight();
                            util.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).setLayoutParams(params1);
                            if (imageViews[imageIndex] != null) {
                                imageViews[imageIndex].setSelected(true);
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
    }

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

        util.getView(mActivity, R.id.llBtn1).setOnClickListener(this);

        mTotalList.clear();

        mSwipeRefreshLayout = (SwipeRefreshLayout) mActivity.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 (!mIsLoading) {
                    mIsLoading = true;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
                }
            }
        });
        setRefresh(true);

        nodeMandatoryPager = (CustomViewPager) findViewById(R.id.vpNode_M);
        mMandatoryTotalList.clear();
        imageIndex = 0;
        pageAdapter = new ThingsDetailVpAdapter(mActivity, mMandatoryTotalList, this);
        nodeMandatoryPager.setAdapter(pageAdapter);
        nodeMandatoryPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            boolean first = true;
            int lastPosition = -1;

            @Override
            public void onPageSelected(int position) {

                LogUtil.i(TAG, "onPageSelected position : " + position);
                imageIndex = position;

                if (mMandatoryTotalList.size() > 0) {
                    for (int row = 0; row < mMandatoryTotalList.size(); row++) {
                        if (imageViews[row] != null) {
                            imageViews[row].setSelected(false);
                        }
                    }
                    if (imageViews[imageIndex] != null) {
                        imageViews[imageIndex].setSelected(true);
                    }
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffest, int positionOffsetPixels) {

                Dlog.v("onPageScrolled position=" + position + " iPosition=" + imageIndex + " lastPosition=" + lastPosition);

                // view pager 첫번째 페이지 selected 이벤트 발생
        /*if (first && positionOffest == 0 && positionOffsetPixels == 0) {
          onPageSelected(0);
          first = false;
        }*/
            }

            @Override
            public void onPageScrollStateChanged(int state) {

                Dlog.v("onPageScrollStateChanged state=" + state);
            }
        });

        setHomeHubStateTitle();
        if (setHomeHubStateList()) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
        }
    }

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

        mSwipeRefreshLayout.setEnabled(false);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                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.INVISIBLE);
            httpSend.getNodeDetail(mDeviceId, mNodeId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

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

                if (joResult.has(Constants.KEY_DEVICE_NAME)) {
                    deviceName = util.null2string(joResult.get(Constants.KEY_DEVICE_NAME));
                }
                if (joResult.has(Constants.KEY_NODE_ID)) {
                    nodeId = util.null2string(joResult.get(Constants.KEY_NODE_ID));
                }
                if (joResult.has(Constants.KEY_DEVICE_MF_ID)) {
                    deviceMfId = util.null2string(joResult.get(Constants.KEY_DEVICE_MF_ID));
                }
                if (joResult.has(Constants.KEY_ONLINE_STATE)) {
                    onlineState = util.null2string(joResult.get(Constants.KEY_ONLINE_STATE));
                }

                String cmdclsList = util.null2string(joResult.get(Constants.KEY_CMDCLS_LIST));
                String deviceclassTypeId = util.null2string(joResult.get(Constants.KEY_DEVICECLASS_TYPE_ID));
                util.getImageView(mActivity, R.id.ivThingsIcon).setImageResource(util.getImageId(mActivity, "img_" + deviceclassTypeId +
                        "_rule"));
                util.getTextView(mActivity, R.id.tvThingsName).setText(deviceName);

                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(cmdclsList);
                LogUtil.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_DEVICE_MF_ID, deviceMfId);
                        hmTemp.put(Constants.KEY_ONLINE_STATE, onlineState);
                        hmTemp.put(Constants.KEY_DEVICE_NAME, deviceName);
                        LogUtil.i(TAG, "hmTemp : " + hmTemp.toString());
                        mTotalList.add(hmTemp);
                    }
                }

                //disp node
                setNodeDisp();
                mIsLoading = false;
                setHomeHubStateAll();
                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if (errorCode.equals("401")) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(mActivity, Constants.MSG997, errorMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

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

        switch (msgId) {

            case Constants.MSG998:
                util.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), 10);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 메뉴 선택 시 처리.
     *
     * @param list 메뉴 리스트
     */
    private void msgAlertList(ArrayList<HashMap<String, Object>> list) {

        try {
            mDialogListBuilder = new DialogCustomList.Builder(mActivity);
            mDialogListBuilder.setList(list);
            mDialogListBuilder.setPositiveButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                    Dlog.v("which = " + which);
                    switch (which) {
                        case 1:
                            break;
                        case 2:
                            intent = new Intent(mActivity, ThingsNameChange.class);
                            String deviceId = util.null2string(mTotalList.get(0).get(Constants.KEY_DEVICE_ID));
                            intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                            String deviceName = util.null2string(mTotalList.get(0).get(Constants.KEY_DEVICE_NAME));
                            intent.putExtra(Constants.EXTRA_DEVICE_NAME, deviceName);
                            String nodeId = util.null2string(mTotalList.get(0).get(Constants.KEY_NODE_ID));
                            intent.putExtra(Constants.EXTRA_NODE_ID, nodeId);
                            util.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_THINGS_NAME_CHANGE);
                            break;
                        case 3:
                            break;
                        case 4:
                            break;
                        case 5:
                            break;
                        case 6:
                            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
                            break;
                        case 7:
                            break;
                        case 8:
                            break;
                        case 9:
                            break;
                        case 10:
                            break;
                        case 11:
                            break;
                        case 12:
                            break;
                        case 15:
                            break;
                        case 16:
                            break;
                        default:
                            break;
                    }
                }
            });
            mDialogListBuilder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Dlog.v("which = " + which);
                    dialog.dismiss();
                }
            });
            mDialogListBuilder.create().show();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

        intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, mIsReloadFinish);
        mActivity.setResult(RESULT_CANCELED, intent);
        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;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                mActivity.setResult(RESULT_CANCELED, new Intent());
                finish();
            }
        }
    }

    /**
     * UI display.
     */
    public void setNodeDisp() {

        try {
            Boolean isOptionFirst = true;
            mMandatoryTotalList.clear();
            util.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).removeAllViews();
            for (int row = 0; row < mTotalList.size(); row++) {
                HashMap<String, Object> hmItem = new HashMap<String, Object>();
                hmItem = mTotalList.get(row);

                String cmdclsMandatoryYn = util.null2string(hmItem.get(Constants.KEY_CMDCLS_MANDATORY_YN));
                if ("Y".equals(cmdclsMandatoryYn)) {
                    mMandatoryTotalList.add(hmItem);
                    LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
                            util.getScaleVal(mActivity, 24), util.getScaleVal(mActivity, 10));
                    imageViews[mMandatoryTotalList.size() - 1] = new ImageView(mActivity);
                    imageViews[mMandatoryTotalList.size() - 1].setImageResource(R.drawable.d_common_bullet_circle2);
                    imageViews[mMandatoryTotalList.size() - 1].setLayoutParams(params2);
                    imageViews[mMandatoryTotalList.size() - 1].setPadding(util.getScaleVal(mActivity, 7), 0
                            , util.getScaleVal(mActivity, 7), 0);
                    imageViews[mMandatoryTotalList.size() - 1].setSelected(false);
                    util.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).addView(imageViews[mMandatoryTotalList.size() - 1]);
                } else {
                    optionCount++;
                    final String onlineState = util.null2string(hmItem.get(Constants.KEY_ONLINE_STATE));

                    final String unit = util.null2string(hmItem.get(Constants.KEY_UNIT));
                    String cmdclsTypeId = util.null2string(hmItem.get(Constants.KEY_CMDCLS_TYPE_ID));

                    String contentValue = util.null2string(hmItem.get(Constants.KEY_CONTENT_VALUE));

                    String tempValue = "";
                    String select = util.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_BG_DEFAULT");
                    if ("".equals(contentValue)) {
                        tempValue = util.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_" + select);
                        contentValue = select;
                    } else {
                        tempValue = util.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_" + contentValue);
                    }
                    final LinearLayout childView = (LinearLayout) View.inflate(this, R.layout.row_things_detail_list, null);
                    if (isOptionFirst) {
                        isOptionFirst = false;
                        util.getLinearLayout(mActivity, R.id.llNode_O).removeAllViews();
                        util.getView(childView, R.id.vEmp).setVisibility(View.VISIBLE);
                    } else {
                        util.getView(childView, R.id.vEmp).setVisibility(View.GONE);
                    }

                    util.getView(childView, R.id.llRowBody1).setVisibility(View.GONE);
                    util.getView(childView, R.id.llRowBody2).setVisibility(View.VISIBLE);

                    final View vLoding = util.getView(childView, R.id.llLoading2);
                    String requestTime = util.null2string(hmItem.get(Constants.KEY_REQUEST_TIME));
                    if (!"".equals(requestTime)) {
                        vLoding.setVisibility(View.VISIBLE);
                    } else {
                        vLoding.setVisibility(View.GONE);
                    }
                    String cmdclsName = util.null2string(hmItem.get(Constants.KEY_CMDCLS_NAME));
                    util.getTextView(childView, R.id.tvRowBody2_Title).setText(cmdclsName);

                    util.getView(childView, R.id.btnRowBody2_Control).setTag(row);
                    util.getView(childView, R.id.btnRowBody2_Control).setVisibility(View.GONE);
                    int cmdclsType = util.null2int(hmItem.get(Constants.KEY_CMDCLS_TYPE_ID));
                    switch (cmdclsType) {
                        //SENSOR_BINARY
                        case Constants.CMDCLS_TYPE_ID_11001:
                        case Constants.CMDCLS_TYPE_ID_11002:
                        case Constants.CMDCLS_TYPE_ID_11003:
                        case Constants.CMDCLS_TYPE_ID_11004:
                        case Constants.CMDCLS_TYPE_ID_11005:
                        case Constants.CMDCLS_TYPE_ID_11006:
                        case Constants.CMDCLS_TYPE_ID_11007:
                        case Constants.CMDCLS_TYPE_ID_11008:
                        case Constants.CMDCLS_TYPE_ID_11009:
                        case Constants.CMDCLS_TYPE_ID_11010:
                        case Constants.CMDCLS_TYPE_ID_11011:
                        case Constants.CMDCLS_TYPE_ID_11012:
                        case Constants.CMDCLS_TYPE_ID_11013:
                        case Constants.CMDCLS_TYPE_ID_11014:
                        case Constants.CMDCLS_TYPE_ID_11015:
                        case Constants.CMDCLS_TYPE_ID_11016:
                        case Constants.CMDCLS_TYPE_ID_11017:
                        case Constants.CMDCLS_TYPE_ID_11018:
                            util.getTextView(childView, R.id.tvRowBody2_Body).setText(tempValue);

                            if ("OFF".equals(onlineState) || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-");
                            }
                            break;
                        //SWITCH_BINARY
                        case Constants.CMDCLS_TYPE_ID_17001:
                        case Constants.CMDCLS_TYPE_ID_17002:
                        case Constants.CMDCLS_TYPE_ID_17003:
                        case Constants.CMDCLS_TYPE_ID_17004:
                        case Constants.CMDCLS_TYPE_ID_17005:
                        case Constants.CMDCLS_TYPE_ID_17006:
                            util.getTextView(childView, R.id.tvRowBody2_Body).setText(tempValue);
                            util.getView(childView, R.id.btnRowBody2_Control).setVisibility(View.VISIBLE);

                            if (contentValue.equals(select)) {
                                util.getView(childView, R.id.btnRowBody2_Control)
                                        .setBackgroundResource(R.drawable.img_things_list_btn_onoff_on);
                            } else {
                                util.getView(childView, R.id.btnRowBody2_Control)
                                        .setBackgroundResource(R.drawable.img_things_list_btn_onoff_off);
                            }

                            util.getView(childView, R.id.btnRowBody2_Control).setOnClickListener(new View.OnClickListener() {
                                int tag = 0;
                                String value = "";

                                @Override
                                public void onClick(View view) {

                                    tag = (int) view.getTag();
                                    String cmdclsTypeId = util.null2string(mTotalList.get(tag).get(Constants.KEY_CMDCLS_TYPE_ID));
                                    String contentValue = util.null2string(mTotalList.get(tag).get(Constants.KEY_CONTENT_VALUE));
                                    if (contentValue.equals(util.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId +
                                            "_BG_DEFAULT"))) {
                                        value = "ON";
                                    } else {
                                        value = "OFF";
                                    }
                                    vLoding.setVisibility(View.VISIBLE);
                                    onCallAction1(tag, value);
                                }
                            });
                            break;
                        case Constants.CMDCLS_TYPE_ID_17008:
                            // 미터초기화
                            util.getTextView(childView, R.id.tvRowBody2_Body).setVisibility(View.GONE);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT);
                            params.setMargins(0, 0, util.getScaleVal(mActivity, 10), 0);
                            util.getView(childView, R.id.btnRowBody2_Control).setLayoutParams(params);
                            util.getView(childView, R.id.btnRowBody2_Control).setVisibility(View.VISIBLE);
                            if ("OFF".equals(onlineState)
                                    || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getView(childView, R.id.btnRowBody2_Control)
                                        .setBackgroundResource(R.drawable.img_things_list_btn_disable);
                            } else {
                                util.getView(childView, R.id.btnRowBody2_Control)
                                        .setBackgroundResource(R.drawable.img_things_list_btn_active);
                            }
                            LogUtil.i(TAG, "tempValue - " + tempValue);
                            util.getButton(childView, R.id.btnRowBody2_Control).setText(tempValue);

                            // 버튼에 들어가는 default padding 값을 없앤다.
                            util.getButton(childView, R.id.btnRowBody2_Control).setMinWidth(0);
                            util.getButton(childView, R.id.btnRowBody2_Control).setMinHeight(0);
                            util.getButton(childView, R.id.btnRowBody2_Control).setMinimumWidth(0);
                            util.getButton(childView, R.id.btnRowBody2_Control).setMinimumHeight(0);

                            util.getButton(childView, R.id.btnRowBody2_Control).setPadding(30, 30, 30, 30);
                            util.getView(childView, R.id.btnRowBody2_Control).setOnClickListener(new View.OnClickListener() {
                                int tag = 0;
                                String value = "";

                                @Override
                                public void onClick(View view) {

                                    if ("OFF".equals(onlineState) || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                        return;
                                    }

                                    tag = (int) view.getTag();
                                    value = "ON";
                                    vLoding.setVisibility(View.VISIBLE);
                                    onCallAction1(tag, value);
                                }
                            });

                            break;
                        case Constants.CMDCLS_TYPE_ID_36002:
                            util.getTextView(childView, R.id.tvRowBody2_Body).setText(tempValue);
                            util.getView(childView, R.id.btnRowBody2_Control).setVisibility(View.VISIBLE);

                            util.getView(childView, R.id.btnRowBody2_Control).setBackgroundResource(
                                    R.drawable.img_things_list_btn_lockunlock_lock);
                            util.getView(childView, R.id.btnRowBody2_Control).setOnClickListener(new View.OnClickListener() {
                                int tag = 0;

                                String value = "";

                                @Override
                                public void onClick(View view) {

                                    tag = (int) view.getTag();
                                    value = "CLOSE";
                                    vLoding.setVisibility(View.VISIBLE);
                                    onCallAction1(tag, value);
                                }
                            });
                            break;

                        // SENSOR_MULTILEVEL
                        case Constants.CMDCLS_TYPE_ID_12001:
                        case Constants.CMDCLS_TYPE_ID_12002:
                        case Constants.CMDCLS_TYPE_ID_12003:
                        case Constants.CMDCLS_TYPE_ID_12004:
                        case Constants.CMDCLS_TYPE_ID_12005:
                        case Constants.CMDCLS_TYPE_ID_12006:
                        case Constants.CMDCLS_TYPE_ID_12007:
                        case Constants.CMDCLS_TYPE_ID_12008:
                        case Constants.CMDCLS_TYPE_ID_12009:
                        case Constants.CMDCLS_TYPE_ID_12010:
                        case Constants.CMDCLS_TYPE_ID_12011:
                        case Constants.CMDCLS_TYPE_ID_12012:
                        case Constants.CMDCLS_TYPE_ID_12013:
                        case Constants.CMDCLS_TYPE_ID_12014:
                        case Constants.CMDCLS_TYPE_ID_12015:
                        case Constants.CMDCLS_TYPE_ID_12016:
                        case Constants.CMDCLS_TYPE_ID_12017:
                        case Constants.CMDCLS_TYPE_ID_12018:
                        case Constants.CMDCLS_TYPE_ID_12019:
                        case Constants.CMDCLS_TYPE_ID_12020:
                        case Constants.CMDCLS_TYPE_ID_12021:
                        case Constants.CMDCLS_TYPE_ID_12022:
                        case Constants.CMDCLS_TYPE_ID_12023:
                        case Constants.CMDCLS_TYPE_ID_12024:
                        case Constants.CMDCLS_TYPE_ID_12025:
                        case Constants.CMDCLS_TYPE_ID_12026:
                        case Constants.CMDCLS_TYPE_ID_12027:
                        case Constants.CMDCLS_TYPE_ID_12028:
                        case Constants.CMDCLS_TYPE_ID_12029:
                        case Constants.CMDCLS_TYPE_ID_12030:
                        case Constants.CMDCLS_TYPE_ID_12031:
                        case Constants.CMDCLS_TYPE_ID_12032:
                        case Constants.CMDCLS_TYPE_ID_12033:
                        case Constants.CMDCLS_TYPE_ID_12034:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;

                        //METER_CURRENT
                        case Constants.CMDCLS_TYPE_ID_15001:
                        case Constants.CMDCLS_TYPE_ID_15002:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                        //METER_TOTAL
                        case Constants.CMDCLS_TYPE_ID_16001:
                        case Constants.CMDCLS_TYPE_ID_16002:
                        case Constants.CMDCLS_TYPE_ID_16003:
                        case Constants.CMDCLS_TYPE_ID_16004:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                        //SWITCH_MULTILEVEL
                        case Constants.CMDCLS_TYPE_ID_18001:
                        case Constants.CMDCLS_TYPE_ID_18002:
                        case Constants.CMDCLS_TYPE_ID_18003:
                        case Constants.CMDCLS_TYPE_ID_18004:
                        case Constants.CMDCLS_TYPE_ID_18005:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                        //THERMOSTAT_SETPOINT
                        case Constants.CMDCLS_TYPE_ID_19001:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                        // METER
                        case Constants.CMDCLS_TYPE_ID_29001:
                        case Constants.CMDCLS_TYPE_ID_29002:
                        case Constants.CMDCLS_TYPE_ID_29003:
                        case Constants.CMDCLS_TYPE_ID_29004:
                        case Constants.CMDCLS_TYPE_ID_29005:
                        case Constants.CMDCLS_TYPE_ID_29006:
                        case Constants.CMDCLS_TYPE_ID_29007:
                        case Constants.CMDCLS_TYPE_ID_29008:
                        case Constants.CMDCLS_TYPE_ID_29009:
                        case Constants.CMDCLS_TYPE_ID_29010:
                        case Constants.CMDCLS_TYPE_ID_29011:
                        case Constants.CMDCLS_TYPE_ID_29012:
                        case Constants.CMDCLS_TYPE_ID_29013:
                        case Constants.CMDCLS_TYPE_ID_29014:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                        //BATTERY
                        case Constants.CMDCLS_TYPE_ID_30001:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                        //SYSTEM
                        case Constants.CMDCLS_TYPE_ID_34006:
                        case Constants.CMDCLS_TYPE_ID_34007:
                        case Constants.CMDCLS_TYPE_ID_34008:
                        case Constants.CMDCLS_TYPE_ID_34009:
                        case Constants.CMDCLS_TYPE_ID_34010:
                        case Constants.CMDCLS_TYPE_ID_34011:
                        case Constants.CMDCLS_TYPE_ID_34012:
                        case Constants.CMDCLS_TYPE_ID_34013:
                        case Constants.CMDCLS_TYPE_ID_34014:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                        default:
                            if (contentValue.equals("none")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            } else {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText(contentValue + unit);
                            }
                            if (onlineState.equals("OFF") || mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                                util.getTextView(childView, R.id.tvRowBody2_Body).setText("-" + unit);
                            }
                            break;
                    }
                    util.getLinearLayout(mActivity, R.id.llNode_O).addView(childView);
                }
            }
            callVpReLoad();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onListReload() {
        //        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_MEMBER_DEVICES), 10);
        // do something
    }

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

    @Override
    public void onCallAction(int callType, int position) {

        switch (callType) {
            case 3:
                // 실행하기
                requestValue = pageAdapter.getHttpValue();
                cmdclsId = util.null2string(mMandatoryTotalList.get(position).get(Constants.KEY_CMDCLS_ID));
                String cmdclsCode = util.null2string(mMandatoryTotalList.get(position).get(Constants.KEY_CMDCLS_CODE));

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

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

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

                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_NODE_COMMAND), 10);
                break;
            default:
                break;
        }

    }

    /**
     * 노드 제어.
     *
     * @param position data index
     * @param value    제어 요청 값
     */
    public void onCallAction1(int position, String value) {

        // 실행하기
        requestValue = value;
        cmdclsId = util.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_ID));
        String contentValue = util.null2string(mTotalList.get(position).get(Constants.KEY_CONTENT_VALUE));
        String cmdclsCode = util.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_CODE));

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

        Dlog.v("requestValue", requestValue);
        Dlog.v("contentValue", contentValue);
        Dlog.v("KEY_cmdcls_id", cmdclsId);
        String cmdclsTypeId = util.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_TYPE_ID));
        String tempValue = util.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_" + requestValue);

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

        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_NODE_COMMAND),
                Constants.HANDLER_DELAY_MILLIS);
    }

    /**
     * 서비스 허브에 노드 제어를 요청한다.
     */
    private void sendWsNodeCommand() {
        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);
        sendParams.put(Constants.KEY_COMMAND_TYPE, Constants.WEBSOCKET_COMM_TYPE_CONTROL);
        sendParams.put(Constants.KEY_CMDCLS_ID, cmdclsId);
        sendParams.put(Constants.KEY_CMDCLS_VALUE, requestValue);
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getiSelect_Servicehub_Request_Id());

        webSocketService.send(Constants.WEBSOCKET_SEND_NODE_COMMAND, sendParams);
    }

    /**
     * {@link ThingsDetail#sendWsNodeCommand() 노드 제어} 요청 결과.
     *
     * @param joResult 결과 json object
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsNodeCommand(JSONObject joResult) throws JSONException {
        String resultCode = util.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        if (resultCode.equals("00")) {
            String resultDeviceId = util.null2string(joResult.get(Constants.KEY_DEVICE_ID));
            String resultNodeId = util.null2string(joResult.get(Constants.KEY_NODE_ID));
            String resultRequestTime = util.null2string(joResult.get(Constants.KEY_REQUEST_TIME));
            int loadingRow = 0;
            for (int row = 0; row < mTotalList.size(); row++) {

                String deviceId = util.null2string(mTotalList.get(row).get(Constants.KEY_DEVICE_ID));
                String nodeId = util.null2string(mTotalList.get(row).get(Constants.KEY_NODE_ID));
                if (resultDeviceId.equals(deviceId) && resultNodeId.equals(nodeId)) {
                    mTotalList.get(row).put(Constants.KEY_REQUEST_TIME, resultRequestTime);
                    loadingRow = row;
                    LogUtil.v(TAG, "resultRequestTime =" + resultRequestTime);
                    break;
                }
            }
            // 제어 요청 10초 후까지 응답이 없으면 타임아웃 처리.
            loadingHandler.sendEmptyMessageDelayed(loadingRow, 10000);
        } else {
            util.setShowToast(mActivity, util.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
        }
        setHomeHubStateList();
    }

    /**
     * {@link ThingsDetail#sendWsNodeCommand() 노드 제어} 처리 후 결과를 푸쉬받는다.
     *
     * @param joResult 결과 json object
     *
     * @exception JSONException json parsing exception
     * @see ThingsDetail#resultWsNodeCommand(JSONObject)
     */
    private void notificationWsNodeCommandResult(JSONObject joResult) throws JSONException {
        String resultDeviceId = util.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        String resultNodeId = util.null2string(joResult.get(Constants.KEY_NODE_ID));
        String resultRequestTime = util.null2string(joResult.get(Constants.KEY_REQUEST_TIME));
        for (int row = 0; row < mTotalList.size(); row++) {

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

                LogUtil.v(TAG, "resultRequestTime =" + resultRequestTime);
                break;
            }
        }
        setNodeDisp();
        setHomeHubStateList();
    }

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

        for (int row1 = 0; row1 < mTotalList.size(); row1++) {
            String tempDeviceId2 = util.null2string(mTotalList.get(row1).get(Constants.KEY_DEVICE_ID));
            String tempNodeId2 = util.null2string(mTotalList.get(row1).get(Constants.KEY_NODE_ID));
            if (!tempDeviceId1.equals(tempDeviceId2) || !tempNodeId1.equals(tempNodeId2)) {
                return;
            }
            String contentValue = util.null2string(hmContentValue.get(mTotalList.get(row1).get(Constants.KEY_CMDCLS_ID)));
            LogUtil.i(TAG, "cmdcls_id : " + util.null2string(mTotalList.get(row1).get(Constants.KEY_CMDCLS_ID)));
            LogUtil.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);
            }
            if (!tempOnlineState1.isEmpty()) {
                mTotalList.get(row1).put(Constants.KEY_ONLINE_STATE, tempOnlineState1);
            }
            LogUtil.i(TAG, "mTotalList : " + mTotalList.toString());
        }
        setNodeDisp();
        setHomeHubStateList();
    }

    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();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}