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

package com.ntels.onecable.view.things;

import com.google.android.gms.analytics.GoogleAnalytics;

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.MainInterface;
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.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.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

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

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

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

    private static final String TAG = FragmentThings.class.getSimpleName();
    private static final int MSG_COM_G_DEVICES = 1;
    private static final int MSG_COM_WS_NODE_COMMAND = 2;
    private static final int MSG_COM_WS_NODE_RELOAD = 3;
    private static final int MSG_COM_D_CLOUD_NODE = 4;
    private static final int MSG_COM_WS_NODE_DELETE = 5;
    /**
     * The Com handler.
     */
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    /*툴바 관련*/
    private Toolbar toolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<HashMap<String, Object>>();
    private int type = 0;
    private WebSocketService webSocketService;
    private boolean isBound = false;
    /*리스트 관련*/
    private FragmentThingsAdapter dataAdapter;
    private RecyclerView rcvList;
    private SwipeRefreshLayout swipeRefreshLayout;
    private GridLayoutManager glmList;
    private LinearLayoutManager llmList;
    private DialogCustomList.Builder dialogListBuilder;
    private boolean loading = false;
    private boolean isListHeader = false;
    private boolean isListFooter = false;
    private boolean isListFooterVisible = false;
    private int listColumnsCnt = 1;
    /*공통*/
    private Activity act;
    private AppConfig appConfig;
    private MainInterface callback;
    private Intent intent;
    private Util util = new Util();
    /**
     * 노드 제어 타임아웃 체크 리스너.
     */
    Handler loadingHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            LogUtil.i(TAG, "loadingHandler::handleMessage!!!");
            LogUtil.i(TAG, "loading : " + loading);
            super.handleMessage(msg);
            int row = msg.what;
            if (!loading) {
                if (row >= 0) {
                    Object requestTime = alTotalList.get(row).get(Constants.KEY_REQUEST_TIME);
                    if (requestTime != null && !requestTime.toString().isEmpty()) {
                        alTotalList.get(row).put(Constants.KEY_REQUEST_TIME, "");
                        setHomeHubStateList();
                        Toast.makeText(act, R.string.MSG917, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };
    private CustomDialog customDialog = new CustomDialog();
    private String callHttpDeviceId = "";
    private String callHttpNodeId = "";
    private String callHttpRequestValue = "";
    private String callHttpCmdclsId = "";
    private int thingsAction = 0;
    private String actName = "";
    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 if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_REGISTER_RESULT)) {
                    notificationWsNodeRegisterResult(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODES_RELOAD)) {
                    resultWsNodeReload(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_DELETE_RESULT)) {
                    notificationWsNodeDelete(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) {

            if (!util.getTopActivityName(act).equals("view.Main")) {
                return;
            }
            switch (code) {
                case Constants.WEBSOCKET_ERROR_TIMEOUT:
                    LogUtil.i(TAG, "WEBSOCKET_ERROR_TIMEOUT!!!");
                    for (HashMap<String, Object> hm : alTotalList) {
                        hm.put(Constants.KEY_REQUEST_TIME, "");
                    }
                    break;
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    LogUtil.i(TAG, "WEBSOCKET_ERROR_NOT_CONNECTED!!!");
                    customDialog.msgAlert(act, Constants.MSG807);
                    break;
                default:
                    break;
            }
            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 onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            callback = (MainInterface) activity;
        } catch (ClassCastException ex) {
            throw new ClassCastException(activity.toString() + " must implement MainInterface");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Dlog.v("onCreate()");
        Intent intent = new Intent(getActivity(), WebSocketService.class);
        getActivity().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onStop() {

        super.onStop();
        Dlog.v("onStop()");
        GoogleAnalytics.getInstance(act).reportActivityStop(act);
    }

    @Override
    public void onStart() {

        super.onStart();
        Dlog.v("onStart()");
        GoogleAnalytics.getInstance(act).reportActivityStart(act);
    }

    @Override
    public void onPause() {

        super.onPause();
        Dlog.v("onPause()");
//        if (webSocketService != null) {
//            if (webSocketService.isWebSocketConnected()) {
//                webSocketService.webSocketDisconnect();
//            }
//        }
    }

    @Override
    public void onResume() {

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

//        if (webSocketService != null) {
//            if (!webSocketService.isWebSocketConnected()) {
//                webSocketService.webSocketConnect();
//            }
//        }
    }

    @Override
    public void onDestroy() {

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

        if (isBound) {
            webSocketService.removeWebSocketResponse(webSocketResponse);
            getActivity().unbindService(serviceConnection);
            isBound = false;
        }
        loadingHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_things, container, false);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        Dlog.v("onActivityCreated().");
        Dlog.v(savedInstanceState == null ? "true" : "false");

        act = getActivity();
        actName = "Things_List";
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        util.callActGoogleAnalytics(actName);

        setToolbar();

        displayListView();
    }

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

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

        util.getTextView(toolbar, R.id.tvToolbarTitle1).setText(util.getString(act, R.string.layout_things_01));
        util.getTextView(toolbar, R.id.tvToolbarTitle2).setText("");
        util.getTextView(toolbar, R.id.tvToolbarTitle3).setText("");
        util.getTextView(toolbar, R.id.tvToolbarTitle4).setText("");

        util.getView(toolbar, R.id.btnToolbarMore).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

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

                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    menus.add(util.getPopMenu(9));
                    menus.add(util.getPopMenu(3));
                    menus.add(util.getPopMenu(20));
                }
                msgAlertList(menus);
            }
        });

        util.getView(toolbar, R.id.btnToolbarClose).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                util.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                dataAdapter.setListCheck(false);
                dataAdapter.notifyDataSetChanged();
                setRefresh(true);
            }
        });
    }

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

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

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

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

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

        Boolean isListLoad = false;

        swipeRefreshLayout.setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Master).setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Guest).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Master).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Guest).setVisibility(View.GONE);

        util.getView(act, R.id.llNoHub_NoHome_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Master_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNoHub_Guest_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Master_Smartcity).setVisibility(View.GONE);
        util.getView(act, R.id.llNodata_Guest_Smartcity).setVisibility(View.GONE);

        if (appConfig.getCtrtGroupId().equals("")) {
            //홈그룹 없을경우
            util.getView(act, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
            dataAdapter.setListCheck(false);
            dataAdapter.notifyDataSetChanged();
            setRefresh(false);
        } else {
            //홈그룹 있을경우

            LogUtil.e(TAG, "Homegrp id - " + appConfig.getCtrtGroupId());

            if (!appConfig.getIsHomegrpHomehub()) {
                //홈그룹은 있고 홈허브가 없는경우
                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    util.getView(act, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
                    dataAdapter.setListCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                } else {
                    util.getView(act, R.id.llNoHub_Guest).setVisibility(View.VISIBLE);
                    dataAdapter.setListCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                }
            } else {
                if (alTotalList.size() > 0) {
                    swipeRefreshLayout.setVisibility(View.VISIBLE);
                } else {
                    if (!loading) {
                        if (!swipeRefreshLayout.isRefreshing()) {
                            if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                                util.getView(act, R.id.llNodata_Master).setVisibility(View.VISIBLE);
                                util.getTextView(act, R.id.tvNodata_Master_Title).setText(R.string.layout_nodata_desc_04);
                            } else {
                                util.getView(act, R.id.llNodata_Guest).setVisibility(View.VISIBLE);
                                util.getTextView(act, R.id.tvNodata_Guest_Title).setText(R.string.layout_nodata_desc_01);
                            }
                        }
                    }
                    dataAdapter.setListCheck(false);
                }
                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    dataAdapter.setFooterVisible(true);
                } else {
                    dataAdapter.setFooterVisible(false);
                }
                dataAdapter.notifyDataSetChanged();
                isListLoad = true;
            }
        }
        //        Dlog.v("Things setHomeHubStateList()");
        return isListLoad;
    }

    /**
     * 리스트를 보여준다.
     */
    private void displayListView() {

        util.getView(act, R.id.llNodata_Master).setOnClickListener(this);
        util.getView(act, R.id.llNoHub_Master).setOnClickListener(this);
        util.getViewUnderline(act, R.id.tvWidthdraw);
        util.getView(act, R.id.tvWidthdraw).setOnClickListener(this);
        util.getViewUnderline(act, R.id.tvConnect);

        alTotalList.clear();

        swipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swiperefreshlayou);
        swipeRefreshLayout.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);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {

                if (!dataAdapter.getListCheck()) {
                    if (!loading) {
                        onListReload();
                        if (!webSocketService.isWebSocketConnected()) {
                            webSocketService.webSocketConnect();
                        }
                    }
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        isListFooter = true;
        isListFooterVisible = true;
        dataAdapter = new FragmentThingsAdapter(act, R.layout.row_things_list, R.layout.row_things_list, R.layout.row_footer_things_list,
                alTotalList, this);
        dataAdapter.setFooterCheck(isListFooter);
        dataAdapter.setFooterVisible(isListFooterVisible);

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

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

                LogUtil.i(TAG, "rcvList onTouch!!");
                if (swipeRefreshLayout.isRefreshing()) {
                    return true;
                }
                return false;
            }
        });
        rcvList.setHasFixedSize(true);
        listColumnsCnt = 2;
        if (listColumnsCnt == 1) {
            llmList = new LinearLayoutManager(act);
            rcvList.setLayoutManager(llmList);
        } else {
            glmList = new GridLayoutManager(act, listColumnsCnt, GridLayoutManager.VERTICAL, false);
            glmList.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

                @Override
                public int getSpanSize(int position) {

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

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

        setHomeHubStateTitle();
        if (!loading) {
            onListReload();
        }
    }

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

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

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llNoHub_Master:
                callback.onHomehubStart();
                break;
            case R.id.tvWidthdraw:
                callback.onHomeMemberWidthdraw();
                break;
            case R.id.llNodata_Master:
                thingsDeviceAdd();
                break;
            default:
                break;
        }
    }

    /**
     * 디바이스 추가 activity로 이동.
     */
    public void thingsDeviceAdd() {

        Intent intent = new Intent(act, ThingsDeviceAdd.class);
        intent.putExtra(Constants.EXTRA_DEVICE_ID, callHttpDeviceId);
        util.callActivityForResult(act, intent, Constants.ACT_THINGS_DEVICE_ADD);
    }

    /**
     * 서비스 허브에 노드 제어를 요청한다.
     *
     * @param position : item position
     */
    private void sendWsNodeCommand(int position) {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_NODE_COMMAND);
        sendParams.put(Constants.KEY_DEVICE_ID, callHttpDeviceId);
        sendParams.put(Constants.KEY_NODE_ID, callHttpNodeId);
        sendParams.put(Constants.KEY_COMMAND_TYPE, Constants.WEBSOCKET_COMM_TYPE_CONTROL);
        sendParams.put(Constants.KEY_CMDCLS_ID, callHttpCmdclsId);
        sendParams.put(Constants.KEY_CMDCLS_VALUE, callHttpRequestValue);
        sendParams.put(Constants.KEY_REQUEST_ID, appConfig.getiSelect_Servicehub_Request_Id());

        webSocketService.send(Constants.WEBSOCKET_SEND_NODE_COMMAND, sendParams);
        // 제어 요청 10초 후까지 응답이 없으면 타임아웃 처리.
        alTotalList.get(position).put(Constants.KEY_REQUEST_TIME, util.getUtcTime());
        loadingHandler.sendEmptyMessageDelayed(position, 10000);
    }

    /**
     * 서비스 허브에 노드제어 요청 결과 수신.
     *
     * @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 = -1;
            for (int row = 0; row < alTotalList.size(); row++) {

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

    /**
     * 서비스 허브에서 노드 제어 처리 후 결과를 푸쉬받는다.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    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));
        int loadingRow = -1;
        for (int row = 0; row < alTotalList.size(); row++) {

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

                Dlog.v("Things jino0 =" + resultRequestTime);
                loadingRow = row;
                break;
            }
        }
        if (loadingRow >= 0) {
            loadingHandler.removeMessages(loadingRow);
        }
        setHomeHubStateList();
    }

    /**
     * 서비스허브에서 노드 컨텐트 정보를 푸쉬받는다.
     *
     * @param joResult 노드 컨텐트 json object
     *
     * @exception JSONException json parsing exception
     */
    private void notificationWsNodeContent(JSONObject joResult) throws JSONException {

        LogUtil.i(TAG, "notificationWsNodeContent!!");
        String resultDeviceId = util.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        String resultNodeId = util.null2string(joResult.get(Constants.KEY_NODE_ID));
        String resultCollectTime = util.null2string(joResult.get(Constants.KEY_COLLECT_TIME));
        HashMap<String, Object> hmContentValue = util.jsonToMap(joResult.get(Constants.KEY_CONTENT_VALUE));
        String resultOnlineState = util.null2string(hmContentValue.get(Constants.KEY_ONLINE));

        for (int row = 0; row < alTotalList.size(); row++) {
            String currentDeviceId = util.null2string(alTotalList.get(row).get(Constants.KEY_DEVICE_ID));
            String currentNodeId = util.null2string(alTotalList.get(row).get(Constants.KEY_NODE_ID));
            String contentValue = util.null2string(hmContentValue.get(alTotalList.get(row).get(Constants.KEY_CMDCLS_ID)));
            if (resultDeviceId.equals(currentDeviceId) && resultNodeId.equals(currentNodeId)) {
                if (!contentValue.isEmpty()) {
                    alTotalList.get(row).put(Constants.KEY_CONTENT_VALUE, contentValue);
                }
                if (!resultOnlineState.isEmpty()) {
                    alTotalList.get(row).put(Constants.KEY_ONLINE_STATE, resultOnlineState);
                }
                alTotalList.get(row).put(Constants.KEY_COLLECT_TIME, resultCollectTime);
                LogUtil.i(TAG, "alTotalList : " + alTotalList.toString());
                break;
            }
        }
        setHomeHubStateList();
    }

    /**
     * 서비스허브에서 새로 등록된 노드 정보를 푸쉬받는다.
     *
     * @param joResult 노드 정보 json object
     *
     * @exception JSONException json parsing exception
     */
    private void notificationWsNodeRegisterResult(JSONObject joResult) throws JSONException {

        LogUtil.i(TAG, "notificationWsNodeRegisterResult!!");
        if (!loading) {
            onListReload();
        }
    }

    /**
     * 서비스허브에 노드 동기화를 요청한다.(데이터 동기화 아님)
     */
    private void sendWsNodeReload() {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_NODES_RELOAD);
        sendParams.put(Constants.KEY_DEVICE_ID, appConfig.getSelect_Homegrp_Homehub_Device_Id());
        sendParams.put(Constants.KEY_REQUEST_ID, appConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * 서비스 허브에 노드 동기화 요청 후 결과 수신.
     *
     * @param jsonObject 결과 json object
     */
    private void resultWsNodeReload(JSONObject jsonObject) {

        LogUtil.i(TAG, "resultWsNodeReload!!");
        util.setShowToast(act, util.getString(act, R.string.MSG906), Toast.LENGTH_SHORT);
        if (!loading) {
            onListReload();
        }
    }

    /**
     * 서비스 허브에 노드 삭제를 요청한다.
     */
    private void sendWsNodeDelete() {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_NODE_DELETE);
        sendParams.put(Constants.KEY_DEVICE_ID, appConfig.getSelect_Homegrp_Homehub_Device_Id());
        sendParams.put(Constants.KEY_NODE_ID, callHttpNodeId);
        sendParams.put(Constants.KEY_REQUEST_ID, appConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * 서비스허브에서 노드 삭제 처리 후 결과를 푸쉬받는다.
     *
     * @param jsonObject 결과 json object
     */
    private void notificationWsNodeDelete(JSONObject jsonObject) {

        LogUtil.i(TAG, "notificationWsNodeDelete!!");
        if (!loading) {
            onListReload();
        }
    }

    /**
     * 장치 리스트 조회(회원의 장치 목록을 조회한다.)
     */
    private void sendGetDevices() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {

                @Override
                public void resultResponse(Response result) {

                    resultGetDevices(result);
                }
            });
            alTotalList.clear();
            swipeRefreshLayout.setVisibility(View.GONE);
            httpSend.getDevices();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 장치 리스트 조회(회원의 장치 목록을 조회한다.) 결과
     *
     * @param result 결과 data
     */
    private void resultGetDevices(Response result) {

        loading = false;
        try {
            if (result.getStatusCode() == 200) {
                alTotalList.clear();
                util.getTextView(toolbar, R.id.tvToolbarTitle2).setText("");

//                JSONObject joResult = new JSONObject(result.getContent());
//                Dlog.v(joResult.toString());
//                String devices = util.null2string(joResult.get(Constants.KEY_DEVICES));

//                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(devices);
                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(result.getContent());
                if (alList.size() > 0) {
                    util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(alList.size() + "");
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmTempDevice = new HashMap<String, Object>();
                        hmTempDevice = alList.get(row);
                        alTotalList.add(hmTempDevice);
                    }
                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    alTotalList.add(hmTemp);
                }
                setHomeHubStateAll();
            } else {
                JSONObject joResult = new JSONObject(result.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(act, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(act, Constants.MSG997, errorMsg);
                } else {
                    customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        } finally {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    /**
     * Cloud to Cloud 연동 Node 삭제.
     */
    private void sendDeleteCloudNode() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {

                @Override
                public void resultResponse(Response result) {

                    resultDeleteCloudNode(result);
                }
            });
            swipeRefreshLayout.setVisibility(View.GONE);
            httpSend.D_cloud_devices_device_id_nodes_node_id(callHttpDeviceId, callHttpNodeId, appConfig.getCtrtGroupId(), appConfig
                    .getLogin_Member_Id());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Cloud to Cloud 연동 Node 삭제 결과.
     *
     * @param result 결과 data
     */
    private void resultDeleteCloudNode(Response result) {

        String resultCode = "";
        String resultMsg = "";

        loading = false;
        try {
            JSONObject joResult = new JSONObject(result.getContent());
            if (!joResult.isNull(Constants.KEY_RESULT_CODE)) {
                resultCode = util.null2string(joResult.get(Constants.KEY_RESULT_CODE));
            }
            if (!joResult.isNull(Constants.KEY_RESULT_MSG)) {
                resultMsg = util.null2string(joResult.get(Constants.KEY_RESULT_MSG));
            }
            if (result.getStatusCode() == 200) {

                LogUtil.i(TAG, "cloud node delete result code : " + resultCode);
                if (resultCode.equals("00")) {
                    intent = new Intent(act, ThingsDeviceDel3rd.class);
                    util.callActivityForResultNoAnim(act, intent, Constants.ACT_THINGS_DEVICE_DEL_3RD);
                } else {
                    customDialog.msgAlert(act, Constants.MSG000, "[" + resultCode + "] " + resultMsg);
                    onListReload();
                }
            } else {
                Dlog.v(joResult.toString());
                if (resultCode.equals("401")) {
                    customDialog.msgAlert(act, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    customDialog.msgAlert(act, Constants.MSG997, resultMsg);
                } else {
                    customDialog.msgAlert(act, Constants.MSG807);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        } finally {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

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

        switch (msgId) {

            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {   // ok 선택 시
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
                }
                break;
            default:
                break;
        }
    }

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

        try {
            dialogListBuilder = new DialogCustomList.Builder(act);
            dialogListBuilder.setList(list);
            dialogListBuilder.setPositiveButton(new AlertDialog.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                    Dlog.v("which = " + which);
                    switch (which) {
                        case 1:
                            break;
                        case 2:
                            break;
                        case 3:
                            util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            util.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            dataAdapter.setListCheck(true);
                            dataAdapter.notifyDataSetChanged();
                            setRefresh(false);
                            break;
                        case 4:
                            break;
                        case 5:
                            break;
                        case 6:
                            onListReload();
                            break;
                        case 7:
                            break;
                        case 8:
                            break;
                        case 9:
                            thingsDeviceAdd();
                            break;
                        case 10:
                            break;
                        case 11:
                            break;
                        case 12:
                            break;
                        case 15:
                            break;
                        case 16:
                            break;
                        case 20:
                            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_NODE_RELOAD), 10);
                            break;
                        default:
                            break;
                    }
                }
            });
            dialogListBuilder.setNegativeButton(new AlertDialog.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

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

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

        super.onActivityResult(requestCode, resultCode, data);
        Boolean reloadFlag = false;
        if (resultCode == act.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_THINGS_DEVICE_DEL_01:
                case Constants.ACT_THINGS_DEVICE_DEL_3RD:
                    if (data == null) {
                        return;
                    }
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                        util.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                        dataAdapter.setListCheck(false);
                        setRefresh(true);
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DEVICE_ADD:
                    if (data == null) {
                        return;
                    }
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DETAIL:
                    if (data == null) {
                        return;
                    }
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    } else {
                        setHomeHubStateAll();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_THINGS_DEVICE_DEL_01:
                    if (data == null) {
                        return;
                    }
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DEVICE_ADD:
                    if (data == null) {
                        return;
                    }
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DETAIL:
                    if (data == null) {
                        return;
                    }
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    } else {
                        setHomeHubStateAll();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onListReload() {

        loading = true;
        if (setHomeHubStateList()) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES), 10);
        }
    }

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

    @Override
    public void onCallAction(int callType, int position) {
        // 디바이스 목록이 없으면 아래 코드 수행하지 않음.
        if (alTotalList.size() <= 0) {
            return;
        }

        if (callType == 0) {
            //추가하기
            callHttpDeviceId = appConfig.getSelect_Homegrp_Homehub_Device_Id();
            thingsDeviceAdd();
        } else if (callType == 1) {
            String deviceclassTypeId = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICECLASS_TYPE_ID));
            int deviceclassTypeIdNum = util.null2int(deviceclassTypeId);
            util.callBtnGoogleAnalytics(actName, "ViewDetail_Things", deviceclassTypeId);

            // 상세보기
            if (deviceclassTypeIdNum == Constants.DEVICECLASS_TYPE_ID_40801) {
                String[] numbers = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_SN)).split("-");
                String cameraNumber = numbers[0];
                String userNumber = numbers[1];
                intent = new Intent(act, ThingsCameraDetail.class);
                intent.putExtra(Constants.EXTRA_CAMERA_CAMERA_NUMBER, cameraNumber);
                intent.putExtra(Constants.EXTRA_CAMERA_USER_NUMBER, userNumber);
                util.callActivity(act, intent);
            } else if (deviceclassTypeIdNum == Constants.DEVICECLASS_TYPE_ID_40802) {
                String configuration = util.null2string(alTotalList.get(position).get(Constants.KEY_CONFIGURATION));
                HashMap<String, Object> hmConfigurations = util.parseConfiguration(configuration);
                if (hmConfigurations == null) {
                    // TODO : configuration 없을 시 처리 방법?
                } else {
                    intent = new Intent(act, ThingsDeviceNetatmoCameraDetail.class);
                    intent.putExtra(Constants.EXTRA_REFRESH_TOKEN, util.null2string(hmConfigurations.get(Constants.KEY_REFRESH_TOKEN)));
                    intent.putExtra(Constants.EXTRA_CAMERA_ID, util.null2string(hmConfigurations.get(Constants.KEY_CAMERA_ID)));
                    intent.putExtra(Constants.EXTRA_CAMERA_ON_OFF, util.null2string(alTotalList.get(position).get(Constants
                            .KEY_CONTENT_VALUE)));
                    intent.putExtra(Constants.EXTRA_ONLNIE_STATE, util.null2string(alTotalList.get(position).get(Constants
                            .KEY_ONLINE_STATE)));
                    util.callActivityForResult(act, intent, Constants.ACT_THINGS_DEVICE_NETATMO_CAMERA_DETAIL);
                }
            } else if (deviceclassTypeIdNum == Constants.DEVICECLASS_TYPE_ID_40604) {
                String deviceId = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_ID));
                String nodeId = util.null2string(alTotalList.get(position).get(Constants.KEY_NODE_ID));
                intent = new Intent(act, ThingsDeviceLedBulbDetail.class);
                intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                intent.putExtra(Constants.EXTRA_NODE_ID, nodeId);
                util.callActivityForResult(act, intent, Constants.ACT_THINGS_DETAIL);
            } else {
                String deviceId = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_ID));
                String nodeId = util.null2string(alTotalList.get(position).get(Constants.KEY_NODE_ID));
                intent = new Intent(act, ThingsDetail.class);
                intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                intent.putExtra(Constants.EXTRA_NODE_ID, nodeId);
                util.callActivityForResult(act, intent, Constants.ACT_THINGS_DETAIL);
            }
        } else if (callType == 2) {
            // 삭제하기
            String deviceId = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_ID));
            callHttpDeviceId = deviceId;
            String nodeId = util.null2string(alTotalList.get(position).get(Constants.KEY_NODE_ID));
            callHttpNodeId = nodeId;
            String deviceName = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_NAME));

            intent = new Intent(act, ThingsDeviceDel1st.class);
            intent.putExtra(Constants.EXTRA_DEVICE_NAME, deviceName);
            intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
            intent.putExtra(Constants.EXTRA_NODE_ID, nodeId);

            String deviceModelId = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_MODEL_ID));
            String deviceMfId = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_MF_ID));
            int deviceclassTypeId = util.null2int(alTotalList.get(position).get(Constants.KEY_DEVICECLASS_TYPE_ID));
            String deviceProtocolType = util.null2string(alTotalList.get(position).get(Constants.KEY_DEVICE_PROTOCOL_TYPE));

            if (deviceModelId.equals("HY-11-10A") && deviceMfId.equals("TimeValve")) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_01));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_04));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_01_smartgasvalve);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_01_smartgasvalve_wait);
            } else if (deviceModelId.equals("SPD-01") && deviceMfId.equals("LGU+")) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_05));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_02));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_05));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_02_iotplug);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_02_iotplug_wait);
            } else if (deviceModelId.equals("ZL7261KR-5") && deviceMfId.equals("VisionSecurity")) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_07));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_02));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_06));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_03_smartplug);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_03_smartplug_wait);
            } else if (deviceModelId.equals("ZP3111") && deviceMfId.equals("VisionSecurity")) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_09));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_08));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_04_mutisensor_motion);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_04_mutisensor_motion_wait);
            } else if (deviceModelId.equals("ZS5101") && deviceMfId.equals("VisionSecurity")) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_11));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_10));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_05_shocksensor);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_05_shocksensor_wait);
            } else if (deviceModelId.equals("ZD211x") && deviceMfId.equals("VisionSecurity")) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_11));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_12));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_06_mutisensor_door);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_06_mutisensor_door_wait);
            } else if (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40801) {
                comHandler.sendEmptyMessageDelayed(MSG_COM_WS_NODE_DELETE, 10);
                return;
            } else if (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40802) {
                comHandler.sendEmptyMessageDelayed(MSG_COM_D_CLOUD_NODE, 10);
                return;
            } else if (deviceProtocolType.equalsIgnoreCase("WIRED")) {
                // Weather station을 비롯한 유선 연결기기는 삭제처리하지않는다.
                customDialog.msgAlert(act, Constants.MSG921);
                return;
            } else {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_15));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_13));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_15));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_00_zwave);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_00_zwave_wait);
            }
            util.callActivityForResultNoAnim(act, intent, Constants.ACT_THINGS_DEVICE_DEL_01);
        } else if (callType == 3) {
            // 실행하기
            callHttpRequestValue = dataAdapter.getHttpValue();
            callHttpDeviceId = appConfig.getSelect_Homegrp_Homehub_Device_Id();
            callHttpNodeId = util.null2string(alTotalList.get(position).get(Constants.KEY_NODE_ID));
            callHttpCmdclsId = util.null2string(alTotalList.get(position).get(Constants.KEY_CMDCLS_ID));
            String contentValue = util.null2string(alTotalList.get(position).get(Constants.KEY_CONTENT_VALUE));
            String cmdclsCode = util.null2string(alTotalList.get(position).get(Constants.KEY_CMDCLS_CODE));

            util.callBtnGoogleAnalytics(actName, "Control_Things", cmdclsCode + "_1depth");

            Dlog.v("callHttpRequestValue", callHttpRequestValue);
            Dlog.v("contentValue", contentValue);

            String cmdclsTypeId = util.null2string(alTotalList.get(position).get(Constants.KEY_CMDCLS_TYPE_ID));
            String tempValue = util.getStringValues(act, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_" + callHttpRequestValue);

            if (callHttpRequestValue.equals(contentValue)) {
                util.setShowToast(act, util.getString(act, R.string.MSG899).replaceAll("\\'컨텐츠밸류\\'", tempValue), Toast.LENGTH_SHORT);
                dataAdapter.notifyDataSetChanged();
                return;
            } else {
                util.setVibrator(100);
            }
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_NODE_COMMAND, position, 0), 10);
        }
    }

    /**
     * The mType Incoming handler call back.
     */
    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICES:
                    sendGetDevices();
                    break;
                case MSG_COM_WS_NODE_COMMAND:
                    sendWsNodeCommand(msg.arg1);
                    break;
                case MSG_COM_WS_NODE_RELOAD:
                    sendWsNodeReload();
                    break;
                case MSG_COM_D_CLOUD_NODE:
                    sendDeleteCloudNode();
                    break;
                case MSG_COM_WS_NODE_DELETE:
                    sendWsNodeDelete();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
