/*
 * 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.util.recyclerview.OnStartDragListener;
import com.ntels.onecable.common.util.recyclerview.SimpleItemTouchHelperCallback;
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.support.v7.widget.helper.ItemTouchHelper;
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
        , OnStartDragListener {

    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 mComHandler = new Handler(new IncomingHandlerCallBack());
    /*툴바 관련*/
    private Toolbar toolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> mAlTotalList = new ArrayList<HashMap<String, Object>>();
    private int mType = 0;
    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;
    /*리스트 관련*/
    private FragmentThingsAdapter mDataAdapter;
    private RecyclerView mRcvList;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private GridLayoutManager mGlmList;
    private LinearLayoutManager llmList;
    private DialogCustomList.Builder dialogListBuilder;
    private boolean mIsListEdit = false;
    private boolean mLoading = false;
    private boolean mIsListHeader = false;
    private boolean mIsListFooter = false;
    private boolean mIsListFooterVisible = false;
    private int mListColumnsCnt = 1;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private MainInterface mCallback;
    private Intent mIntent;
    private Util mUtil = new Util();
    /**
     * 노드 제어 타임아웃 체크 리스너.
     */
    Handler loadingHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            LogUtil.i(TAG, "loadingHandler::handleMessage!!!");
            LogUtil.i(TAG, "mLoading : " + mLoading);
            super.handleMessage(msg);
            int row = msg.what;
            if (!mLoading) {
                if (row >= 0) {
                    Object requestTime = mAlTotalList.get(row).get(Constants.KEY_REQUEST_TIME);
                    if (requestTime != null && !requestTime.toString().isEmpty()) {
                        mAlTotalList.get(row).put(Constants.KEY_REQUEST_TIME, "");
                        setHomeHubStateList();
                        Toast.makeText(mActivity, R.string.MSG917, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };
    private ItemTouchHelper mItemTouchHelper;
    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 = 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 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() {
                            mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });*/
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public void onError(int code, String message) {

            if (!mUtil.getTopActivityName(mActivity).equals("view.Main")) {
                return;
            }
            switch (code) {
                case Constants.WEBSOCKET_ERROR_TIMEOUT:
                    LogUtil.i(TAG, "WEBSOCKET_ERROR_TIMEOUT!!!");
                    for (HashMap<String, Object> hm : mAlTotalList) {
                        hm.put(Constants.KEY_REQUEST_TIME, "");
                    }
                    break;
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    LogUtil.i(TAG, "WEBSOCKET_ERROR_NOT_CONNECTED!!!");
                    customDialog.msgAlert(mActivity, 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;
            mWebSocketService = binder.getService();
            mWebSocketService.addWebSocketResponse(webSocketResponse);
            mIsBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            mIsBound = false;
        }
    };

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            mCallback = (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(mActivity).reportActivityStop(mActivity);
    }

    @Override
    public void onStart() {

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

    @Override
    public void onPause() {

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

    @Override
    public void onResume() {

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

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

    @Override
    public void onDestroy() {

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

        if (mIsBound) {
            mWebSocketService.removeWebSocketResponse(webSocketResponse);
            getActivity().unbindService(serviceConnection);
            mIsBound = 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");

        mActivity = getActivity();
        actName = "Things_List";
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        mUtil.callActGoogleAnalytics(actName);

        setToolbar();

        displayListView();
    }

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

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

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

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

                if (mAppConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    menus.add(mUtil.getPopMenu(22));
                    menus.add(mUtil.getPopMenu(9));
                    menus.add(mUtil.getPopMenu(3));
//                    menus.add(mUtil.getPopMenu(20));
                }
                menus.add(mUtil.getPopMenu(6));
                msgAlertList(menus);
            }
        });

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

            @Override
            public void onClick(View view) {

                mUtil.getView(toolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
                mUtil.getView(toolbar, R.id.llToolbarMore).setVisibility(View.GONE);
                mUtil.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                mUtil.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                mDataAdapter.setListCheck(false);
                mDataAdapter.setDeleteCheck(false);
                mDataAdapter.setMoveCheck(false);
                mDataAdapter.notifyDataSetChanged();
                mIsListEdit = false;
                setRefresh(true);
            }
        });
    }

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

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

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

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

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

        Boolean isListLoad = false;

        mSwipeRefreshLayout.setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Master).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Guest).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Master).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Guest).setVisibility(View.GONE);

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

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

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

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

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

        mUtil.getView(mActivity, R.id.llNodata_Master).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llNoHub_Master).setOnClickListener(this);
        mUtil.getViewUnderline(mActivity, R.id.tvWidthdraw);
        mUtil.getView(mActivity, R.id.tvWidthdraw).setOnClickListener(this);
        mUtil.getViewUnderline(mActivity, R.id.tvConnect);

        mAlTotalList.clear();

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

            @Override
            public void onRefresh() {

                if (!mDataAdapter.getListCheck()) {
                    if (!mLoading) {
                        onListReload();
                        if (!mWebSocketService.isWebSocketConnected()) {
                            mWebSocketService.webSocketConnect();
                        }
                    }
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        mIsListFooter = true;
        mIsListFooterVisible = true;
        mDataAdapter = new FragmentThingsAdapter(mActivity
                , R.layout.row_things_list, R.layout.row_things_list, R.layout.row_footer_things_list
                , mAlTotalList, this, this);
        mDataAdapter.setFooterCheck(mIsListFooter);
        mDataAdapter.setFooterVisible(mIsListFooterVisible);

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

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

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

                @Override
                public int getSpanSize(int position) {

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

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

        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mDataAdapter);
        mItemTouchHelper = new ItemTouchHelper(callback);
        mItemTouchHelper.attachToRecyclerView(mRcvList);
        setHomeHubStateTitle();
        if (!mLoading) {
            onListReload();
        }
    }

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

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

    @Override
    public void onClick(View view) {

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

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

        Intent intent = new Intent(mActivity, ThingsDeviceAdd.class);
        intent.putExtra(Constants.EXTRA_DEVICE_ID, callHttpDeviceId);
        mUtil.callActivityForResult(mActivity, 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, mAppConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * 서비스 허브에 노드제어 요청 결과 수신.
     *
     * @param joResult : 결과 json object
     *
     * @exception JSONException : json parsing exception
     */
    private void resultWsNodeCommand(JSONObject joResult) throws JSONException {

        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        if (resultCode.equals("00")) {
            String resultDeviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
            String resultNodeId = mUtil.null2string(joResult.get(Constants.KEY_NODE_ID));
            String resultRequestTime = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_TIME));
            int loadingRow = -1;
            for (int row = 0; row < mAlTotalList.size(); row++) {

                String deviceId = mUtil.null2string(mAlTotalList.get(row).get(Constants.KEY_DEVICE_ID));
                String nodeId = mUtil.null2string(mAlTotalList.get(row).get(Constants.KEY_NODE_ID));
                if (resultDeviceId.equals(deviceId) && resultNodeId.equals(nodeId)) {
                    mAlTotalList.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 {
            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, 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 = 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 = -1;
        for (int row = 0; row < mAlTotalList.size(); row++) {

            String deviceId = mUtil.null2string(mAlTotalList.get(row).get(Constants.KEY_DEVICE_ID));
            String nodeId = mUtil.null2string(mAlTotalList.get(row).get(Constants.KEY_NODE_ID));
            if (resultDeviceId.equals(deviceId) && resultNodeId.equals(nodeId)) {
                mAlTotalList.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 = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        String resultNodeId = mUtil.null2string(joResult.get(Constants.KEY_NODE_ID));
        String resultCollectTime = mUtil.null2string(joResult.get(Constants.KEY_COLLECT_TIME));
        HashMap<String, Object> hmContentValue = mUtil.jsonToMap(joResult.get(Constants.KEY_CONTENT_VALUE));
        String resultOnlineState = mUtil.null2string(hmContentValue.get(Constants.KEY_ONLINE));

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

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

        LogUtil.i(TAG, "notificationWsNodeRegisterResult!!");
        if (!mLoading) {
            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, mAppConfig.getSelect_Homegrp_Homehub_Device_Id());
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getiSelect_Servicehub_Request_Id());

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

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

        LogUtil.i(TAG, "resultWsNodeReload!!");
        mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG906), Toast.LENGTH_SHORT);
        if (!mLoading) {
            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, mAppConfig.getSelect_Homegrp_Homehub_Device_Id());
        sendParams.put(Constants.KEY_NODE_ID, callHttpNodeId);
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getiSelect_Servicehub_Request_Id());

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

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

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

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

        try {
            HttpSend httpSend;

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

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {

                @Override
                public void resultResponse(Response result) {

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

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

        mLoading = false;
        try {
            if (result.getStatusCode() == 200) {
                mAlTotalList.clear();
                mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setText("");

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

//                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(devices);
                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(result.getContent());
                if (alList.size() > 0) {
                    mUtil.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);
                        mAlTotalList.add(hmTempDevice);
                    }
                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    mAlTotalList.add(hmTemp);
                }
                setHomeHubStateAll();
            } else {
                JSONObject joResult = new JSONObject(result.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 (errorCode.equals("401")) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, errorMsg);
                } else if (errorCode.equals("401-106")) {
                    customDialog.msgAlert(mActivity, Constants.MSG997, errorMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        } finally {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

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

        try {
            HttpSend httpSend;

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

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {

                @Override
                public void resultResponse(Response result) {

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

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

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

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

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

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

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {   // ok 선택 시
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), 10);
                }
                break;
            default:
                break;
        }
    }

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

        try {
            dialogListBuilder = new DialogCustomList.Builder(mActivity);
            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:
                            setRefresh(false);
                            mIsListEdit = true;
                            mUtil.getView(toolbar, R.id.llToolbar).setVisibility(View.GONE);
                            mUtil.getView(toolbar, R.id.llToolbarMore).setVisibility(View.VISIBLE);
                            mUtil.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            mUtil.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            mUtil.getTextView(toolbar, R.id.tvToolbarMoreTitle1).setText(mUtil.getString(mActivity, R.string
                                    .layout_context_menu_03));
                            mDataAdapter.setDeleteCheck(true);
                            mDataAdapter.notifyDataSetChanged();
                            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:
                            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_WS_NODE_RELOAD), 10);
                            break;
                        case 21:
                            break;
                        case 22:
                            setRefresh(false);
                            mIsListEdit = true;
                            mUtil.getView(toolbar, R.id.llToolbar).setVisibility(View.GONE);
                            mUtil.getView(toolbar, R.id.llToolbarMore).setVisibility(View.VISIBLE);
                            mUtil.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            mUtil.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            mUtil.getTextView(toolbar, R.id.tvToolbarMoreTitle1).setText(mUtil.getString(mActivity, R.string
                                    .layout_context_menu_22));
                            mDataAdapter.setMoveCheck(true);
                            mDataAdapter.notifyDataSetChanged();
                            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 (data == null) {
            return;
        }
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_THINGS_DEVICE_DEL_01:
                case Constants.ACT_THINGS_DEVICE_DEL_3RD:
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        mUtil.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                        mUtil.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                        mDataAdapter.setListCheck(false);
                        setRefresh(true);
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DEVICE_ADD:
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DETAIL:
                    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:
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DEVICE_ADD:
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    }
                    break;
                case Constants.ACT_THINGS_DETAIL:
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    } else {
                        setHomeHubStateAll();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onListReload() {

        mLoading = true;
        if (setHomeHubStateList()) {
            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_DEVICES), 10);
        }
    }

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

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

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

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

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

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

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

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

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

            String cmdclsTypeId = mUtil.null2string(mAlTotalList.get(position).get(Constants.KEY_CMDCLS_TYPE_ID));
            String tempValue = mUtil.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_" + callHttpRequestValue);

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

    @Override
    public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
        mItemTouchHelper.startDrag(viewHolder);
    }

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

        @Override
        public boolean handleMessage(Message msg) {

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