/*
 * 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.MainInterface;
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.Util;
import com.ntels.onecable.admin.common.util.recyclerview.OnStartDragListener;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
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.content.Intent;
import android.os.Bundle;
import android.os.Handler;
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;

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 :   FragmentThings
 * 2. FileName  :   FragmentThings.java
 * 3. Package   :   com.ntels.onecable.admin.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;
    private static final int MSG_COM_P_DEVICE_SEQ_INIT = 6;
    private static final int MSG_COM_P_DEVICE_SEQ = 7;
    /**
     * 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();
    //    private int mTotalCtrtCnt = 0;
    private int mMyCtrtCnt = 0;


    private int mDevicePosition = 0;
    private ArrayList<String> mDeviceNameList = new ArrayList<String>();
    /**
     * 노드 제어 타임아웃 체크 리스너.
     */
    private Handler loadingHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            Dlog.i(TAG, "loadingHandler::handleMessage!!!");
            Dlog.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, "");
                        dispListChanged();
                        Toast.makeText(mActivity, R.string.MSG917, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };
    private String mSelectDeviceId = "";
    private ItemTouchHelper mItemTouchHelper;
    private CustomDialog mCustomDialog = new CustomDialog();
    private String callHttpDeviceId = "";
    private String callHttpNodeId = "";
    private String callHttpRequestValue = "";
    private String callHttpCmdclsId = "";
    private int thingsAction = 0;
    private String actName = "";


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

        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {
//            if (!mUtil.getTopActivityName(mActivity).equals("view.Main")) {
//                return;
//            }
            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {
                case Constants.WEBSOCKET_ERROR_TIMEOUT:
                    Dlog.i(TAG, "WEBSOCKET_ERROR_TIMEOUT!!!");
                    for (HashMap<String, Object> hm : mAlTotalList) {
                        hm.put(Constants.KEY_REQUEST_TIME, "");
                    }
                    break;
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    Dlog.i(TAG, "WEBSOCKET_ERROR_NOT_CONNECTED!!!");
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                    break;
                default:
                    break;
            }
            dispListChanged();
        }
    }

    private void dispListChanged() {

        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
        mDataAdapter.notifyDataSetChanged();
    }

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

    }

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

    @Override
    public void onResume() {

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

    }

    @Override
    public void onDestroy() {

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

        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();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        mUtil.callActGoogleAnalytics(actName);


        displayListView();
    }


    /**
     * 리스트를 보여준다.
     */
    private void displayListView() {
        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 (!mCallback.getWebSocketService().isWebSocketConnected()) {
//                            mCallback.getWebSocketService().webSocketConnect();
//                        }
                    }
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

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

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

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

                Dlog.i(TAG, "mRcvList onTouch!!");
                if (mSwipeRefreshLayout.isRefreshing()) {
                    return true;
                }
                return false;
            }
        });
        mRcvList.setHasFixedSize(true);
        mListColumnsCnt = 1;
        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 1;
//                        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);


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

    /**
     * 서비스 허브에 노드 제어를 요청한다.
     *
     * @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_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());
        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
        sendParams.put(Constants.KEY_CMDCLS_ID, callHttpCmdclsId);
        sendParams.put(Constants.KEY_CMDCLS_VALUE, callHttpRequestValue);

        mCallback.getWebSocketService().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);
        }
        dispListChanged();
    }

    /**
     * 서비스 허브에서 노드 제어 처리 후 결과를 푸쉬받는다.
     *
     * @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);
        }
        dispListChanged();

    }

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

        Dlog.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));

        Dlog.v("resultDeviceId = " + resultDeviceId);
        Dlog.v("resultNodeId = " + resultNodeId);
        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)));

            Dlog.v("currentDeviceId = " + currentDeviceId);
            Dlog.v("currentNodeId = " + currentNodeId);
            if (resultDeviceId.equals(currentDeviceId) && resultNodeId.equals(currentNodeId)) {
                Dlog.v("contentValue1 = " + contentValue);
                if (!contentValue.isEmpty()) {
                    Dlog.v("contentValue2 = " + contentValue);
                    mAlTotalList.get(row).put(Constants.KEY_CONTENT_VALUE, contentValue);
                }
                if (!resultOnlineState.isEmpty()) {
                    Dlog.v("contentValue3 = " + contentValue);
                    mAlTotalList.get(row).put(Constants.KEY_ONLINE_STATE, resultOnlineState);
                }
                mAlTotalList.get(row).put(Constants.KEY_COLLECT_TIME, resultCollectTime);
                Dlog.i(TAG, "mAlTotalList : " + mAlTotalList.toString());
                break;
            }
        }
        dispListChanged();
    }

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

        Dlog.i(TAG, "notificationWsNodeRegisterResult!!");
        if (!mLoading) {
            onListReload();
        }
    }

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

        Dlog.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);

            // 선택된 홈허브가 없을때 1개인 경우는 무조건 선택 홈허브를 지정하도록 한다
            if (mAppConfig.getDevicesList().size() == 1) {
                httpSend.getNodeList("", mAppConfig.getCustomerCtrtId());
            } else {
                httpSend.getNodeList(mSelectDeviceId, mAppConfig.getCustomerCtrtId());
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void setDevicesData(ArrayList<HashMap<String, Object>> alDevices) {
        mAppConfig.setDevicesList(alDevices);

    }


    /**
     * 장치 리스트 조회(회원의 장치 목록을 조회한다.) 결과
     *
     * @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 ctrt_cnt = mUtil.null2string(joResult.get(Constants.KEY_CTRT_CNT));
                String nodes = mUtil.null2string(joResult.get(Constants.KEY_NODES));
                String devices = mUtil.null2string(joResult.get(Constants.KEY_DEVICES));

//                mTotalCtrtCnt = mUtil.null2int(ctrt_cnt);
                mMyCtrtCnt = 0;
//                디바이스 정보 갱신
                ArrayList<HashMap<String, Object>> alDevices = mUtil.jsonToArrayListMap(devices);
                setDevicesData(alDevices);

                // 현재 ctrtid 한개에 무조건 한개의 디바이스만 있으므로 만약 여러개가 나올경우 전반적으로 수정이 필요함
                mSelectDeviceId = mAppConfig.getFirstHomehubDeviceId();
                mAppConfig.setIsCtrtGroupHomehub(true);
                HashMap<String, Object> hmTempDevice = new HashMap<String, Object>();
                hmTempDevice = mAppConfig.getDevicesList(mSelectDeviceId);
                mAlTotalList.add(hmTempDevice);

                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(nodes);
                if (alList.size() > 0) {
//                    mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setText(alList.size() + "");
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmTempNode = new HashMap<String, Object>();
                        hmTempNode = alList.get(row);
                        mAlTotalList.add(hmTempNode);
                        mMyCtrtCnt++;
                    }
                }
                dispListChanged();
            } else {
                JSONObject joResult = new JSONObject(result.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);
        } 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.MSG934:
                if (btnResult == 1) {   // ok 선택 시
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DEVICE_SEQ_INIT), 10);
                }
                break;
            case Constants.MSG935:
                if (btnResult == 1) {   // ok 선택 시
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_DEVICE_SEQ), 10);
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {   // ok 선택 시
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), 10);
                }
                break;
            default:
                break;
        }
    }

    @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_DETAIL:
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    } else {
                        dispListChanged();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_THINGS_DETAIL:
                    reloadFlag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (reloadFlag) {
                        onListReload();
                    } else {
                        dispListChanged();
                    }
                    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) {
            //추가하기
//            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);

            String deviceId = mUtil.null2string(mAlTotalList.get(position).get(Constants.KEY_DEVICE_ID));
            String nodeId = mUtil.null2string(mAlTotalList.get(position).get(Constants.KEY_NODE_ID));
            Dlog.v("DeviceId = " + deviceId);
            Dlog.v("nodeId = " + nodeId);
            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) {
            // 삭제하기
        } else if (callType == 3) {
            // 실행하기
            callHttpRequestValue = mDataAdapter.getHttpValue();
            callHttpDeviceId = mUtil.null2string(mAlTotalList.get(position).get(Constants.KEY_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;
                default:
                    break;
            }
            return true;
        }
    }
}
