/*
 * Copyright (c) 2016. nTels.co.,ltd. to Present.
 * All rights reserved.
 */

package com.ntels.onecable.view.things;

import com.flask.colorpicker.ColorPickerView;
import com.flask.colorpicker.OnColorSelectedListener;
import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
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.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.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

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

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

    private static final String TAG = ThingsDeviceLedBulbDetail.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 String CMDCLS_ID_BULB = "bulb";
    private static final String CMDCLS_ID_HSB_COLOR = "hsbcolor";
    private static final String CMDCLS_ID_DIMMING = "dimming";
    private static final String CMDCLS_ID_WHITE_LEVEL = "whitelevel";

    private String mDeviceId = "";
    private String mNodeId = "";

    private boolean mIsReloadFinish = false;

    /*툴바 관련*/
    private Toolbar mToolbar;

    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> mTotalList = 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 mUtil = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private String mRequestValue = "";
    private String mCmdclsId = "";
    private WebSocketService webSocketService;
    private boolean isBound = false;
    private ColorPickerView mColorPickerView;
    private SeekBar mDimmingSeekBar;
    private SeekBar mWhiteLevelSeekBar;

    /** 노드 제어 타임아웃 체크 리스너. */
    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, "");
                        setNodeDisplay();
                        setHomeHubStateList();
                    }

                }
            }
        }
    };

    @Override
    public void onDestroy() {

        super.onDestroy();
        Dlog.v("onDestroy()");
        if (isBound) {
            webSocketService.removeWebSocketResponse(webSocketResponse);
            unbindService(serviceConnection);
            isBound = false;
        }
    }

    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;
        }
    };

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

                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.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 = 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 {
                    /*final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mUtil.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();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = ThingsDeviceLedBulbDetail.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_device_ledbulb_detail, null);
        this.setContentView(viewToLoad);

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

        setToolbar();

        displayListView();
    }

    @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();
            }
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                break;
            case R.id.btnRowBody1_Contents_On:
                setPower("ON");
                break;
            case R.id.btnRowBody1_Contents_Off:
                setPower("OFF");
                break;
            default:
                break;
        }
    }

    @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) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), 10);
                }
                break;
            default:
                break;
        }
    }

    Handler comHandler = new Handler(new IncomingHandlerCallBack());

    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;
        }
    }

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

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

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

        mUtil.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(mUtil.getPopMenu(6));

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

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

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

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

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

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

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

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

        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnRowBody1_Contents_On).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnRowBody1_Contents_Off).setOnClickListener(this);
        mUtil.getTextView(this, R.id.btnRowBody1_Contents_On)
                .setText(R.string.CMDCLS_TYPE_ID_40604_ON);
        mUtil.getTextView(this, R.id.btnRowBody1_Contents_Off)
                .setText(R.string.CMDCLS_TYPE_ID_40604_OFF);

        mTotalList.clear();

        mColorPickerView = (ColorPickerView) findViewById(R.id.color_picker_view);
        mColorPickerView.addOnColorSelectedListener(new OnColorSelectedListener() {
            @Override
            public void onColorSelected(int selectedColor) {
                setBulbColor(selectedColor);
            }
        });

        mDimmingSeekBar = (SeekBar) findViewById(R.id.dimming_seekbar);
        mDimmingSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                setDimming(seekBar.getProgress());
            }
        });

        mWhiteLevelSeekBar = (SeekBar) findViewById(R.id.whitelevel_seekbar);
        mWhiteLevelSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                setWhiteLevel(seekBar.getProgress());
            }
        });

        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), Constants.HANDLER_DELAY_MILLIS);
                }
            }
        });
        setRefresh(true);

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

    /**
     * Led Bulb 컬러 변경.
     *
     * @param selectedColor 선택된 컬러
     */
    private void setBulbColor(int selectedColor) {
        float[] hsb = mUtil.rgbToHsb(selectedColor);
        mCmdclsId = CMDCLS_ID_HSB_COLOR;
        mRequestValue = mUtil.getHsbStr(hsb);
        comHandler.sendEmptyMessageDelayed(MSG_COM_WS_NODE_COMMAND, Constants.HANDLER_DELAY_MILLIS);
    }

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

        mSwipeRefreshLayout.setEnabled(false);
    }

    /**
     * 장치 상세조회(해당 장치의 상세 정보를 조회한다. (장치가 보유한 모든 커맨드 클래스 리스트를 보여준다)) 요청.
     */
    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 = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
                String deviceName = "";
                String deviceMfId = "";
                String onlineState = "";
                String nodeId = "";

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

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

                ArrayList<HashMap<String, Object>> alList = mUtil.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
                setNodeDisplay();
                mIsLoading = false;
                setHomeHubStateAll();
                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));

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

    /**
     * 메뉴 선택 시 처리.
     *
     * @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 = mUtil.null2string(mTotalList.get(0)
                                    .get(Constants.KEY_DEVICE_ID));
                            intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                            String deviceName = mUtil.null2string(mTotalList.get(0)
                                    .get(Constants.KEY_DEVICE_NAME));
                            intent.putExtra(Constants.EXTRA_DEVICE_NAME, deviceName);
                            String nodeId = mUtil.null2string(mTotalList.get(0)
                                    .get(Constants.KEY_NODE_ID));
                            intent.putExtra(Constants.EXTRA_NODE_ID, nodeId);
                            mUtil.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();
        }
    }

    /**
     * 서비스 허브에 노드 제어를 요청한다.
     */
    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, mCmdclsId);
        sendParams.put(Constants.KEY_CMDCLS_VALUE, mRequestValue);
        sendParams.put(Constants.KEY_REQUEST_ID,
                mAppConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * {@link ThingsDeviceLedBulbDetail#sendWsNodeCommand() 노드 제어} 요청 결과.
     *
     * @param joResult 결과 json object
     * @throws JSONException json parsing exception
     */
    private void resultWsNodeCommand(JSONObject joResult) throws JSONException {
        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        if ("00".equals(resultCode)) {
            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));
            int loadingRow = 0;
            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));
                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 {
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
        }
        setHomeHubStateList();
    }

    /**
     * {@link ThingsDeviceLedBulbDetail#sendWsNodeCommand() 노드 제어} 처리 후 결과를 푸쉬받는다.
     *
     * @param joResult 결과 json object
     * @throws JSONException json parsing exception
     * @see ThingsDeviceLedBulbDetail#resultWsNodeCommand(JSONObject)
     */
    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));
        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));
            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
     * @throws JSONException json parsing exception
     */
    private void notificationWsNodeContent(JSONObject joResult) throws JSONException {
        LogUtil.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)));
            LogUtil.i(TAG, "cmdcls_id : " + mUtil.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());
        }
        setNodeDisplay();
        setHomeHubStateList();
    }

    /**
     * Led Bulb 밝기 변경.
     *
     * @param progress 밝기 정도 (0 ~ 99)
     */
    private void setDimming(int progress) {
        mCmdclsId = CMDCLS_ID_DIMMING;
        mRequestValue = String.valueOf(progress);
        comHandler.sendEmptyMessageDelayed(MSG_COM_WS_NODE_COMMAND, Constants.HANDLER_DELAY_MILLIS);
    }

    /**
     * Led Bulb 색온도 변경.
     *
     * @param progress 색온도 (0 ~ 100)
     */
    private void setWhiteLevel(int progress) {
        mCmdclsId = CMDCLS_ID_WHITE_LEVEL;
        mRequestValue = String.valueOf(progress);
        comHandler.sendEmptyMessageDelayed(MSG_COM_WS_NODE_COMMAND, Constants.HANDLER_DELAY_MILLIS);
    }

    /**
     * 노드 데이터 셋팅.
     */
    private void setNodeDisplay() {
        if (null != mTotalList) {
            for (HashMap hm : mTotalList) {
                if ("OFF".equals(hm.get(mUtil.null2string(Constants.KEY_ONLINE_STATE)))) {
                    mColorPickerView.setEnabled(false);
                    mDimmingSeekBar.setProgressDrawable(getResources().getDrawable(R.drawable.img_things_detail_88_level_bar));
                    mDimmingSeekBar.setEnabled(false);
                    mWhiteLevelSeekBar.setProgressDrawable(getResources().getDrawable(R.drawable.img_things_detail_88_level_bar));
                    mWhiteLevelSeekBar.setEnabled(false);
                    mUtil.getView(mActivity, R.id.btnRowBody1_Contents_On).setEnabled(false);
                    mUtil.getView(mActivity, R.id.btnRowBody1_Contents_Off).setEnabled(false);
                    return;
                } else {
                    mColorPickerView.setEnabled(true);
                    mDimmingSeekBar.setProgressDrawable(getResources().getDrawable(R.drawable.d_dimming_seekbar));
                    mDimmingSeekBar.setEnabled(true);
                    mWhiteLevelSeekBar.setProgressDrawable(getResources().getDrawable(R.drawable.d_whitelevel_seekbar));
                    mWhiteLevelSeekBar.setEnabled(true);
                    mUtil.getView(mActivity, R.id.btnRowBody1_Contents_On).setEnabled(true);
                    mUtil.getView(mActivity, R.id.btnRowBody1_Contents_Off).setEnabled(true);
                    String cmdclsId = mUtil.null2string(hm.get(Constants.KEY_CMDCLS_ID));
                    switch (cmdclsId) {
                        case CMDCLS_ID_BULB:
                            break;
                        case CMDCLS_ID_HSB_COLOR:
                            String contentValue = mUtil.null2string(
                                    hm.get(Constants.KEY_CONTENT_VALUE));
                            if (!"".equals(contentValue)) {
                                int rgbColor = mUtil.hsbToRgb(contentValue);
                                mColorPickerView.setInitialColor(rgbColor, false);
                            }
                            break;
                        case CMDCLS_ID_DIMMING:
                            int dimming = mUtil.null2int(hm.get(Constants.KEY_CONTENT_VALUE));
                            mDimmingSeekBar.setProgress(dimming);
                            break;
                        case CMDCLS_ID_WHITE_LEVEL:
                            int whiteLevel = mUtil.null2int(hm.get(Constants.KEY_CONTENT_VALUE));
                            mWhiteLevelSeekBar.setProgress(whiteLevel);
                            break;
                    }
                }
            }
        }
    }

    /**
     * Led Bulb power on/off.
     *
     * @param requestValue ON or OFF
     */
    private void setPower(String requestValue) {
        String contentValue = mUtil.null2string(mTotalList.get(0)
                .get(Constants.KEY_CONTENT_VALUE));
        String cmdclsTypeId = mUtil.null2string(mTotalList.get(0)
                .get(Constants.KEY_CMDCLS_TYPE_ID));
        String tempValue = mUtil.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId
                + "_" + mRequestValue);

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

        mCmdclsId = CMDCLS_ID_BULB;
        mRequestValue = requestValue;
        comHandler.sendEmptyMessageDelayed(MSG_COM_WS_NODE_COMMAND, Constants.HANDLER_DELAY_MILLIS);
    }

}