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

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


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

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

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

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

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


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

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

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

                }
            }
        }
    };

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                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_PROFILE_UPDATE)) {
                    resultWsNodeProfileUpdateCommand(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_PROFILE_UPDATE_RESULT)) {
                    notificationWsNodeProfileUpdateResult(jsonObject);
                } else {
                    /*final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });*/
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {

            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                    break;
                default:
                    break;
            }
            setNodeDisp();
            setHomeHubStateList();
        }
    }

    ;

    @Override
    public void onStop() {

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

    @Override
    public void onPause() {

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

    @Override
    public void onResume() {

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

    @Override
    public void onDestroy() {

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


    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        setIsWebSocket(true);

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

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

        setToolbar();

        displayListView();
    }

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

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

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

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

                ArrayList<HashMap<String, Object>> alMenuList = new ArrayList<HashMap<String, Object>>();

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

                alMenuList.add(mUtil.getPopMenu(6));

                msgAlertList(alMenuList);
            }
        });
        mUtil.getView(mToolbar, R.id.btnToolbarUpdate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String msg = getString(R.string.MSG931, mDeviceName);
                mCustomDialog.msgAlert(mActivity, Constants.MSG995, msg, R.string.MSG_TITLE_008
                        , mUtil.getString(mActivity, R.string.MSG_BTN_YES), mUtil.getString(mActivity, R.string.MSG_BTN_NO));


            }
        });
    }

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

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

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

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

                } else {
                    //홈그룹은 있고 홈허브가 온라인인 경우
                    mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
                    mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
                }
            }
        }
    }

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

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

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

        if (mMandatoryTotalList.size() > 0) {
//            if (mOptionCount == 0) {
//                mPageAdapter.setHideDivider(false);
//            } else {
//                mPageAdapter.setHideDivider(true);
//            }
            mNodeMandatoryPager.getAdapter().notifyDataSetChanged();
//            mUtil.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).setVisibility(View.GONE);

//            mNodeMandatoryPager.post(new Runnable() {
//                @Override
//                public void run() {
//
//                    try {
//                        if (mMandatoryTotalList.size() > 1) {
////                            mUtil.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).setVisibility(View.VISIBLE);
//
//                            ViewGroup.LayoutParams params1 = mUtil.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).getLayoutParams();
//                            params1.height = mUtil.getView(mActivity, R.id.vpNode_M).getHeight();
//                            mUtil.getLinearLayout(mActivity, R.id.llvpNode_M_Icon).setLayoutParams(params1);
//                            if (mImageViews[mImageIndex] != null) {
//                                mImageViews[mImageIndex].setSelected(true);
//                            }
//                        }
//                    } catch (Exception ex) {
//                        ex.printStackTrace();
//                    }
//                }
//            });
        }
    }

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

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

        mUtil.getTextView(mActivity, R.id.tvDeviceName).setText(mUtil.getString(mActivity, R.string.layout_things_detail_02)
                + mAppConfig.getHomehubDeviceName(mDeviceId));

        mTotalList.clear();

        mSwipeRefreshLayout = (SwipeRefreshLayout) mActivity.findViewById(R.id.swiperefreshlayou);
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light,
                android.R.color.holo_green_light, android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if (!mIsLoading) {
                    mIsLoading = true;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
                }
            }
        });
        setRefresh(true);

        mNodeMandatoryPager = (CustomViewPager) findViewById(R.id.vpNode_M);
        mMandatoryTotalList.clear();
        mImageIndex = 0;
        mPageAdapter = new ThingsDetailVpAdapter(mActivity, mDeviceId, mMandatoryTotalList, this);
        mNodeMandatoryPager.setAdapter(mPageAdapter);
//        mNodeMandatoryPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            boolean first = true;
//            int lastPosition = -1;
//
//            @Override
//            public void onPageSelected(int position) {
//
//                LogUtil.i(TAG, "onPageSelected position : " + position);
//                mImageIndex = position;
//
//                if (mMandatoryTotalList.size() > 0) {
//                    for (int row = 0; row < mMandatoryTotalList.size(); row++) {
//                        if (mImageViews[row] != null) {
//                            mImageViews[row].setSelected(false);
//                        }
//                    }
//                    if (mImageViews[mImageIndex] != null) {
//                        mImageViews[mImageIndex].setSelected(true);
//                    }
//                }
//            }
//
//            @Override
//            public void onPageScrolled(int position, float positionOffest, int positionOffsetPixels) {
//
//                Dlog.v("onPageScrolled position=" + position + " iPosition=" + mImageIndex + " lastPosition=" + lastPosition);
//
//                // view pager 첫번째 페이지 selected 이벤트 발생
//        /*if (first && positionOffest == 0 && positionOffsetPixels == 0) {
//          onPageSelected(0);
//          first = false;
//        }*/
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//                Dlog.v("onPageScrollStateChanged state=" + state);
//            }
//        });

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

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

        mSwipeRefreshLayout.setEnabled(false);
    }

    @Override
    public void onClick(View view) {

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

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

        try {
            HttpSend httpSend;

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

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

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

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

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

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

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

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

                String cmdclsList = mUtil.null2string(joResult.get(Constants.KEY_CMDCLS_LIST));
                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(cmdclsList);
                LogUtil.i(TAG, "alList : " + alList.toString());
                if (alList.size() > 0) {
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                        hmTemp = alList.get(row);
                        hmTemp.put(Constants.KEY_DEVICE_ID, deviceId);
                        hmTemp.put(Constants.KEY_NODE_ID, nodeId);
                        hmTemp.put(Constants.KEY_DEVICECLASS_TYPE_ID, deviceclassTypeId);
                        hmTemp.put(Constants.KEY_ONLINE_STATE, onlineState);
                        hmTemp.put(Constants.KEY_DEVICE_NAME, deviceName);
                        LogUtil.i(TAG, "hmTemp : " + hmTemp.toString());
                        mTotalList.add(hmTemp);
                    }
                }

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

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

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

        switch (msgId) {

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

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

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

                    dialog.dismiss();
                    Dlog.v("which = " + which);
                    switch (which) {
                        case 1:
                            break;
                        case 2: {
                            mIntent = new Intent(mActivity, ThingsNameChange.class);
                            String deviceId = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_DEVICE_ID));
                            mIntent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                            String deviceName = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_DEVICE_NAME));
                            mIntent.putExtra(Constants.EXTRA_DEVICE_NAME, deviceName);
                            String nodeId = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_NODE_ID));
                            mIntent.putExtra(Constants.EXTRA_NODE_ID, nodeId);
                            mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_NAME_CHANGE);
                        }
                        break;
                        case 3: {
                            // 삭제하기
                            String deviceId = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_DEVICE_ID));
                            String nodeId = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_NODE_ID));
                            String deviceName = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_DEVICE_NAME));

                            String onlineState = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_ONLINE_STATE));

                            Intent intent;
                            if (onlineState.equals("OFF")) {
                                intent = new Intent(mActivity, ThingsDeviceDelOffStep1.class);
                            } else {
                                intent = new Intent(mActivity, ThingsDeviceDelStep0.class);
                            }
                            intent.putExtra(Constants.EXTRA_DEVICE_NAME, deviceName);
                            intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                            intent.putExtra(Constants.EXTRA_NODE_ID, nodeId);

                            int deviceclassTypeId = mUtil.null2int(mTotalList.get(0).get(Constants.KEY_DEVICECLASS_TYPE_ID));
                            String deviceProtocolType = mUtil.null2string(mTotalList.get(0).get(Constants.KEY_DEVICE_PROTOCOL_TYPE));

                            if (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40302) {
                                intent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string
                                        .layout_things_device_add_03));
                                intent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, 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 (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40402) {
                                intent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string
                                        .layout_things_device_add_05));
                                intent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, 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 (deviceclassTypeId.equals("ZL7261KR-5") ) {
//                mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_07));
//                mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, 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 (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40107) {
                                intent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string
                                        .layout_things_device_add_09));
                                intent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, 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")) {
//                mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_11));
//                mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, 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 (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40102) {
                                intent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string
                                        .layout_things_device_add_11));
                                intent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, 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) {
//                                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을 비롯한 유선 연결기기는 삭제처리하지않는다.
                                mCustomDialog.msgAlert(mActivity, Constants.MSG921);
                                return;
                            } else {
                                intent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string
                                        .layout_things_device_add_15));
                                intent.putExtra(Constants.EXTRA_DEVICE_DESC, mUtil.getString(mActivity, R.string
                                        .layout_things_device_add_del_13));
                                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, mUtil.getString(mActivity, 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);
                            }

                            if (onlineState.equals("OFF")) {
                                mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_THINGS_DEVICE_DEL_OFF_STEP1);
                            } else {
                                mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_THINGS_DEVICE_DEL_STEP0);
                            }
                        }
                        break;
                        case 4:
                            break;
                        case 5:
                            break;
                        case 6:
                            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES_DEVICE_ID), 10);
                            break;
                        case 7:
                            break;
                        case 8:
                            break;
                        case 9:
                            break;
                        case 10:
                            break;
                        case 11:
                            break;
                        case 12:
                            break;
                        case 15:
                            break;
                        case 16:
                            break;
                        default:
                            break;
                    }
                }
            });
            mDialogListBuilder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                @Override
                                public void onClick(View view) {

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

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

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

                                @Override
                                public void onClick(View view) {

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

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

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

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

                                String value = "";

                                @Override
                                public void onClick(View view) {

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

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

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

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

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

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

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

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

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

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

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

    }

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

        // 실행하기
        mRequestValue = value;
        mCmdClsId = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_ID));
        String contentValue = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CONTENT_VALUE));
        String cmdclsCode = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CMDCLS_CODE));

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

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

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

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

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

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

    /**
     * {@link ThingsDetail#sendWsNodeCommand() 노드 제어} 요청 결과.
     *
     * @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 = 0;
            for (int row = 0; row < mTotalList.size(); row++) {

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

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

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

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

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

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

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

            dialog_dismiss();
            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
            if (resultCode.equals("00")) {

                mUtil.getView(mActivity, R.id.tvUpdateAlram).setVisibility(View.INVISIBLE);
                mUtil.getView(mToolbar, R.id.btnToolbarUpdate).setVisibility(View.INVISIBLE);
                mCustomDialog.msgAlert(mActivity, Constants.MSG932);
            } else {
                Dlog.v(joResult.toString());
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if ("401".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if ("401-106".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        try {
            mUtil.getView(mActivity, R.id.llBtn2).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * {@link ThingsDetail#sendWsNodeCommand() 노드 제어} 처리 후 결과를 푸쉬받는다.
     *
     * @param joResult 결과 json object
     *
     * @exception JSONException json parsing exception
     * @see ThingsDetail#resultWsNodeCommand(JSONObject)
     */
    private void notificationWsNodeCommandResult(JSONObject joResult) throws JSONException {
        String resultDeviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        String resultNodeId = mUtil.null2string(joResult.get(Constants.KEY_NODE_ID));
        String resultRequestTime = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_TIME));
        for (int row = 0; row < mTotalList.size(); row++) {

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

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

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

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

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