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

package com.ntels.kneet.v3.view.things;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.List_Interface;
import com.ntels.kneet.v3.common.c_interface.Main_Interface;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.LogUtil;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.util.recyclerview.DividerItemDecoration;
import com.ntels.kneet.v3.common.websocket.WebSocketService;
import com.ntels.kneet.v3.common.websocket.onWebSocketResponse;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.dialog.Dialog_Custom_List;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

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

public class Fragment_Things extends Fragment implements View.OnClickListener,
                                                         CustomDialog.OnMsgAlterToResult,
                                                         List_Interface {
    private static final String TAG = Fragment_Things.class.getSimpleName();

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

    /*통신 관련*/
    private              ArrayList<HashMap<String, Object>> alTotalList                                        = new ArrayList<HashMap<String, Object>>();
    private              int                                iType                                              = 0;
    private static final int                                MSG_COM_G_DEVICES                                  = 1;
    private static final int                                MSG_COM_G_DEVICES_NODES                            = 2;
    private static final int                                MSG_COM_WS_NODE_COMMAND                            = 3;
//    private static final int                                MSG_COM_P_DEVICES_DEVICE_ID_NODES_NODE_ID_COMMANDS = 3;
    private              WebSocketService                   webSocketService;
    private              boolean                            bBound                                             = false;

    /*리스트 관련*/
    private Fragment_Things_Adapter    dataAdapter;
    private RecyclerView               rcvList;
    private SwipeRefreshLayout         swipeRefreshLayout;
    private GridLayoutManager          glmList;
    private LinearLayoutManager        llmList;
    private Dialog_Custom_List.Builder dialog_list_builder;
    private ScheduledFuture            scheduledFuture;
    private boolean loading            = false;
    private boolean bListHeader        = false;
    private boolean bListFooter        = false;
    private boolean bListFooterVisible = false;
    private boolean bListFooterAnd     = false;
    private int     iListColumnsCnt    = 1;

    /*공통*/
    private Activity       act;
    private AppConfig      appConfig;
    private Main_Interface mCallback;
    private Intent         intent;
    private Util         util                     = new Util();
    private CustomDialog customDialog             = new CustomDialog();
    private String       sCallType                = "";
    private String       sCall_HTTP_device_id     = "";
    private String       sCall_HTTP_node_id       = "";
    private String       sCall_HTTP_request_value = "";
    private String       sCall_HTTP_cmdcls_id     = "";
    private Boolean      bPollingPause            = false;
    private Boolean      bPollingCancel           = false;
    private Boolean      bActStop                 = false;
    private int          iThingsAction            = 0;
    private String       sActName                 = "";

    /**
     *  WebSocket listener
     *
     */
    private onWebSocketResponse webSocketResponse = new onWebSocketResponse() {
        @Override
        public void onWebSocketResponse(String result) {
            try {

                JSONObject jsonObject = new JSONObject(result);
                String messageType = util.null2string(jsonObject.get(Constants.WEBSOCKET_KEY_MESSAGE_TYPE));
                LogUtil.i(TAG, "websocket message type : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if ( jsonObject.has(Constants.WEBSOCKET_KEY_RESULT_CODE) ) {
                    resultCode = util.null2string(jsonObject.get(Constants.WEBSOCKET_KEY_RESULT_CODE));
                }
                if ( jsonObject.has(Constants.WEBSOCKET_KEY_RESULT_MSG) ) {
                    resultMsg = util.null2string(jsonObject.get(Constants.WEBSOCKET_KEY_RESULT_MSG));
                }
                if ( messageType.equals(Constants.WEBSOCKET_TYPE_NODE_COMMAND_RESULT) ) {
                    result_WS_node_command(jsonObject);
                } else if ( messageType.equals(Constants.WEBSOCKET_TYPE_NODE_CONTENT) ) {
                    notification_WS_node_content(jsonObject);
                } else {
                    /*final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            util.setShowToast(act, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });*/
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onWebSocketError(String message) {

        }
    };

    /**
     *  Service bind listener
     *
     */
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtil.i(TAG, "");
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            webSocketService = binder.getService();
            webSocketService.addWebSocketResponse(webSocketResponse);
            bBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bBound = false;
        }
    };

    //    @Override public void onAttach(Context context) {
    //
    //        super.onAttach(context);
    //
    //        Activity activity;
    //
    //        if ( context instanceof Activity ) {
    //            activity = (Activity) context;
    //            try {
    //                mCallback = (Main_Interface) activity;
    //            } catch (ClassCastException e) {
    //                throw new ClassCastException(activity.toString() + " must implement Main_Interface");
    //            }
    //        }
    //    }

    @Override public void onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            mCallback = (Main_Interface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement Main_Interface");
        }
    }

    //    @Override public void onAttach(Context context) {
    //
    //        super.onAttach(context);
    //
    //        Activity activity;
    //
    //        if ( context instanceof Activity ) {
    //            activity = (Activity) context;
    //            try {
    //                mCallback = (Main_Interface) activity;
    //            } catch (ClassCastException e) {
    //                throw new ClassCastException(activity.toString() + " must implement Main_Interface");
    //            }
    //        }
    //    }
    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onCreate(Bundle savedInstanceState) {

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

    @Override public void onStop() {

        super.onStop();
        Dlog.v("onStop()");
        bPollingPause = true;
        bActStop = true;
        GoogleAnalytics.getInstance(act).reportActivityStop(act);
    }

    @Override public void onStart() {

        super.onStart();
        Dlog.v("onStart()");
        GoogleAnalytics.getInstance(act).reportActivityStart(act);
    }
    @Override public void onPause() {

        super.onPause();
        Dlog.v("onPause()");
        bPollingPause = true;
        bActStop = true;
    }

    @Override public void onResume() {

        super.onResume();
        Dlog.v("onResume()");
        bPollingPause = false;
        bActStop = false;
    }

    @Override public void onDestroy() {

        super.onDestroy();
        Dlog.v("onDestroy()");
        if ( scheduledFuture != null ) {
            scheduledFuture.cancel(false);
            bPollingPause = true;
        }

        if ( bBound ) {
            webSocketService.removeWebSocketResponse(webSocketResponse);
            getActivity().unbindService(serviceConnection);
            bBound = false;
        }
    }

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

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

        return rootView;
    }

    @Override public void onActivityCreated(Bundle savedInstanceState) {

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

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

        //        Tracker t = appConfig.getTracker(AppConfig.TrackerName.APP_TRACKER);
        //        t.setScreenName(act.getClass().getSimpleName());
        //        t.send(new HitBuilders.AppViewBuilder().build());
        util.callActGoogleAnalytics(sActName);

        setToolbar();

        displayListView();
    }

    private void setToolbar() {

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

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

        util.getView(toolbar, R.id.btnToolbarMore).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {

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

                //                if ( appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON") && appConfig.getSelect_Homegrp_Grade_Code().equals("MAS") ) {
                if ( appConfig.getSelect_Homegrp_Grade_Code().equals("MAS") ) {
                    alMenuList.add(util.getPopMenu(9));
                    alMenuList.add(util.getPopMenu(3));
                }
                MsgAlertList(alMenuList);
            }
        });

        util.getView(toolbar, R.id.btnToolbarClose).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {

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

    public void setHomeHubStateAll() {

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

    public void setHomeHubStateTitle() {

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

    public boolean setHomeHubStateList() {

        Boolean bListLoad = false;
        //        Dlog.v("Things setHomeHubStateList()");

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

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

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

    private void displayListView() {

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

        alTotalList.clear();

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

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

        bListFooter = true;
        bListFooterVisible = true;
        dataAdapter = new Fragment_Things_Adapter(act, R.layout.row_things_list, R.layout.row_things_list, R.layout.row_footer_things_list, alTotalList, this);
        dataAdapter.setFooterCheck(bListFooter);
        dataAdapter.setFooterVisible(bListFooterVisible);

        rcvList = (RecyclerView) getView().findViewById(R.id.rcvList);
        rcvList.setHasFixedSize(true);
        iListColumnsCnt = 2;
        if ( iListColumnsCnt == 1 ) {
            llmList = new LinearLayoutManager(act);
            rcvList.setLayoutManager(llmList);
        } else {
            glmList = new GridLayoutManager(act, iListColumnsCnt, GridLayoutManager.VERTICAL, false);
            glmList.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override public int getSpanSize(int position) {

                    int iPositionType = dataAdapter.getItemViewType(position);
                    int iTotalConut = dataAdapter.getItemCount();
                    int iValueConut = dataAdapter.getItemCount();
                    if ( bListHeader ) {
                        iValueConut = iTotalConut - 1;
                    }

                    if ( iPositionType == dataAdapter.TYPE_HEADER ) {
                        return glmList.getSpanCount();
                    } else {
                        return dataAdapter.getItemViewType(position) == 1 ? 1 : (iValueConut % iListColumnsCnt == 1 ? glmList.getSpanCount() : 1);
                    }
                }
            });
            rcvList.setLayoutManager(glmList);
        }
        rcvList.addItemDecoration(new DividerItemDecoration(getActivity(), R.drawable.list_color_line_01));
        //        rcvList.setItemAnimator(new FadeInAnimator());
        //        rcvList.setAdapter(dataAdapter);
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        rcvList.setAdapter(scaleAdapter);

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

    private void setRefresh(boolean bVal) {

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

    @Override public void onClick(View v) {

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

    public void Things_Device_Add() {

        Intent intent = new Intent(act, Things_Device_Add.class);
        util.callActivityForResult(act, intent, Constants.ACT_THINGS_DEVICE_ADD);
    }

    private void setThingsPolling() {

        Dlog.v("Things setThingsPolling");
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        scheduledFuture = scheduler.scheduleAtFixedRate(runnable, 3, 3, TimeUnit.SECONDS);
    }

    Runnable runnable   = new Runnable() {
        public void run() {

            Dlog.v("Things bPollingCancel", bPollingCancel);
            Dlog.v("Things bPollingPause", bPollingPause);

            if ( bPollingCancel ) {
                scheduledFuture.cancel(false);
            }
            if ( !bPollingPause ) {
                Dlog.v("Things setThingsPolling");
                if ( appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON") ) {
                    if ( alTotalList.size() > 1 ) {
                        Dlog.v("Things jino");
                        send_G_devices_nodes();
                    }
                }
            }
        }
    };
    Handler  ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICES:
                    send_G_devices();
                    break;
                case MSG_COM_G_DEVICES_NODES:
                    //dialog_show();
                    send_G_devices_nodes();
                    break;
                case MSG_COM_WS_NODE_COMMAND:
                    //dialog_show();
//                    send_P_devices_device_id_nodes_node_id_commands();
                    send_WS_node_command();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_WS_node_command
     * 2. ClassName :
     * 3. Comment   : [Send]서비스 허브에 노드 제어를 요청한다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void send_WS_node_command() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.WEBSOCKET_KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_NODE_COMMAND);
        sendParams.put(Constants.WEBSOCKET_KEY_DEVICE_ID, sCall_HTTP_device_id);
        sendParams.put(Constants.WEBSOCKET_KEY_NODE_ID, sCall_HTTP_node_id);
        sendParams.put(Constants.WEBSOCKET_KEY_COMMAND_TYPE, Constants.WEBSOCKET_COMM_TYPE_CONTROL);
        sendParams.put(Constants.WEBSOCKET_KEY_CMDCLS_ID, sCall_HTTP_cmdcls_id);
        sendParams.put(Constants.WEBSOCKET_KEY_CMDCLS_VALUE, sCall_HTTP_request_value);
        sendParams.put(Constants.WEBSOCKET_KEY_REQUEST_ID, appConfig.getiSelect_Servicehub_Request_Id());

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

    /**
     * <PRE>
     * 1. MethodName: result_WS_node_command
     * 2. ClassName :
     * 3. Comment   : [Result]서비스 허브에 노드 제어를 요청한다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void result_WS_node_command(JSONObject joResult) throws JSONException {
        String sResultHTTP_device_id = util.null2string(joResult.get(Constants.WEBSOCKET_KEY_DEVICE_ID));
        String sResultHTTP_node_id = util.null2string(joResult.get(Constants.WEBSOCKET_KEY_NODE_ID));
        String sResultHTTP_request_time = util.null2string(joResult.get(Constants.WEBSOCKET_KEY_REQUEST_TIME));
        for ( int iRow = 0; iRow < alTotalList.size(); iRow++ ) {

            String sHTTP_device_id = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_device_id));
            String sHTTP_node_id = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_node_id));
            if ( sResultHTTP_device_id.equals(sHTTP_device_id) && sResultHTTP_node_id.equals(sHTTP_node_id) ) {
                alTotalList.get(iRow).put(Constants.HTTP_request_time, sResultHTTP_request_time);

                Dlog.v("Things jino0 =" + sResultHTTP_request_time);
                break;
            }
        }
        setHomeHubStateList();
    }

    /**
     * <PRE>
     * 1. MethodName: notification_WS_node_content
     * 2. ClassName :
     * 3. Comment   : [notification]서비스 허브에서 노드 컨텐트 정보를 받는다.
     * 4. Developer : 정백호
     * 5. Created   : 2016. 07.
     * </PRE>
     */
    private void notification_WS_node_content(JSONObject joResult) throws JSONException {
        LogUtil.i(TAG, "notification_WS_node_content!!");
        String sTempHTTP_device_id1 = util.null2string(joResult.get(Constants.WEBSOCKET_KEY_DEVICE_ID));
        String sTempHTTP_node_id1 = util.null2string(joResult.get(Constants.WEBSOCKET_KEY_NODE_ID));
        String sTempHTTP_collect_time1 = util.null2string(joResult.get(Constants.WEBSOCKET_KEY_COLLECT_TIME));
        HashMap<String, Object> hmContentValue = util.jsonToMap(joResult.get(Constants.WEBSOCKET_KEY_CONTENT_VALUE));
        String sTempHTTP_online_state1 = util.null2string(hmContentValue.get(Constants.WEBSOCKET_KEY_ONLINE));

        for ( int iRow1 = 0; iRow1 < alTotalList.size(); iRow1++ ) {
            String sTempHTTP_device_id2 = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_device_id));
            String sTempHTTP_node_id2 = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_node_id));
            String sTempHTTP_request_time2 = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_request_time));
            String sContentValue = util.null2string(hmContentValue.get(alTotalList.get(iRow1).get(Constants.HTTP_cmdcls_id)));
            if ( sTempHTTP_device_id1.equals(sTempHTTP_device_id2) && sTempHTTP_node_id1.equals(sTempHTTP_node_id2) ) {
                alTotalList.get(iRow1).put(Constants.HTTP_content_value, sContentValue);
                alTotalList.get(iRow1).put(Constants.HTTP_collect_time, sTempHTTP_collect_time1);
                alTotalList.get(iRow1).put(Constants.HTTP_online_state, sTempHTTP_online_state1);
                LogUtil.i(TAG, "alTotalList : " + alTotalList.toString());
                if ( !sTempHTTP_request_time2.equals("") ) {
                    if ( !sTempHTTP_collect_time1.equals("") ) {
                        if ( util.str2long(util.UTCtoLocal4(sTempHTTP_collect_time1.replaceAll("Z", ""))) > util.str2long(util.UTCtoLocal4(sTempHTTP_request_time2.replaceAll(
                                "Z", ""))) ) {
                            iThingsAction = 0;
                            alTotalList.get(iRow1).put(Constants.HTTP_request_time, "");
                            Dlog.v("Things jino1");
                        }
                    }
                }
                break;
            }
        }
        for ( int iRow1 = 0; iRow1 < alTotalList.size(); iRow1++ ) {
            String sHTTP_request_time = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_request_time));
            if ( !sHTTP_request_time.equals("") ) {
                Dlog.v("Things jino5");
                Dlog.v("Things jino5 sHTTP_request_time=" + sHTTP_request_time);
                Dlog.v("Things jino5 util.getRealTime1()=" + util.getRealTime1());
                Dlog.v("Things jino5 10초후=" + util.stringDateAddTime(util.UTCtoLocal4(sHTTP_request_time.replaceAll("Z", "")), 10000));
                if ( util.str2long(util.getRealTime1()) > util.str2long(util.stringDateAddTime(util.UTCtoLocal4(sHTTP_request_time.replaceAll("Z", "")), 10000)) ) {
                    iThingsAction++;
                    alTotalList.get(iRow1).put(Constants.HTTP_request_time, "");
                }
            }
        }
        if ( iThingsAction == 3 ) {
            util.setShowToast(act, util.getString(act, R.string.MSG867), Toast.LENGTH_SHORT);
        }
        setHomeHubStateList();
    }

    /**
     * <PRE>
     * 1. MethodName: send_G_devices_nodes
     * 2. ClassName :
     * 3. Comment   : [Send][GET]복수 - 노드(커맨드클래스) 마지막 상태 값 조회(복수 노드(커맨드클래스)의 마지막 상태 값을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_G_devices_nodes() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(act, false);
            //httpSend = new HttpSend(act);

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

                    result_G_devices_nodes(result);
                }
            });

            String sTemp = "";
            for ( int iRow = 0; iRow < alTotalList.size() - 1; iRow++ ) {
                String sTempHTTP_device_id = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_device_id));
                String sTempHTTP_node_id = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_node_id));
                //                String sTempHTTP_collect_time = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_collect_time));

                //                sTemp += (sTemp.equals("") ? "" : ",") + sTempHTTP_device_id + "_" + sTempHTTP_node_id + "_" + sTempHTTP_collect_time;
                sTemp += (sTemp.equals("") ? "" : ",") + sTempHTTP_device_id + "_" + sTempHTTP_node_id;
            }

            bPollingPause = true;
            httpSend.G_devices_nodes(sTemp);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_G_devices_nodes
     * 2. ClassName :
     * 3. Comment   : [Result][GET]복수 - 노드(커맨드클래스) 마지막 상태 값 조회(복수 노드(커맨드클래스)의 마지막 상태 값을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_G_devices_nodes(Response rpResult) {

        loading = false;
        try {
            if ( rpResult.getStatusCode() == 200 ) {
                if ( !rpResult.getContent().equals("") ) {
                    ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(rpResult.getContent());
                    for ( int iRow = 0; iRow < alList.size(); iRow++ ) {
                        String sTempHTTP_device_id1 = util.null2string(alList.get(iRow).get(Constants.HTTP_device_id));
                        String sTempHTTP_node_id1 = util.null2string(alList.get(iRow).get(Constants.HTTP_node_id));
                        String sTempHTTP_content_value1 = util.null2string(alList.get(iRow).get(Constants.HTTP_content_value));
                        String sTempHTTP_collect_time1 = util.null2string(alList.get(iRow).get(Constants.HTTP_collect_time));
                        String sTempHTTP_online_state1 = util.null2string(alList.get(iRow).get(Constants.HTTP_online_state));

                        for ( int iRow1 = 0; iRow1 < alTotalList.size() - 1; iRow1++ ) {
                            String sTempHTTP_device_id2 = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_device_id));
                            String sTempHTTP_node_id2 = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_node_id));
                            String sTempHTTP_request_time2 = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_request_time));
                            if ( sTempHTTP_device_id1.equals(sTempHTTP_device_id2) && sTempHTTP_node_id1.equals(sTempHTTP_node_id2) ) {
                                Dlog.v("sTempHTTP_device_id1", sTempHTTP_device_id1);
                                Dlog.v("sTempHTTP_device_id2", sTempHTTP_device_id2);
                                Dlog.v("sTempHTTP_node_id1", sTempHTTP_node_id1);
                                Dlog.v("sTempHTTP_node_id2", sTempHTTP_node_id2);
                                alTotalList.get(iRow1).put(Constants.HTTP_content_value, sTempHTTP_content_value1);
                                alTotalList.get(iRow1).put(Constants.HTTP_collect_time, sTempHTTP_collect_time1);
                                alTotalList.get(iRow1).put(Constants.HTTP_online_state, sTempHTTP_online_state1);
                                if ( !sTempHTTP_request_time2.equals("") ) {
                                    if ( !sTempHTTP_collect_time1.equals("") ) {
                                        if ( util.str2long(util.UTCtoLocal4(sTempHTTP_collect_time1.replaceAll("Z", ""))) > util.str2long(util.UTCtoLocal4(sTempHTTP_request_time2.replaceAll(
                                                "Z", ""))) ) {
                                            iThingsAction = 0;
                                            alTotalList.get(iRow1).put(Constants.HTTP_request_time, "");
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                    for ( int iRow1 = 0; iRow1 < alTotalList.size() - 1; iRow1++ ) {
                        String sHTTP_request_time = util.null2string(alTotalList.get(iRow1).get(Constants.HTTP_request_time));
                        if ( !sHTTP_request_time.equals("") ) {
                            if ( util.str2long(util.getRealTime1()) > util.str2long(util.stringDateAddTime(util.UTCtoLocal4(sHTTP_request_time.replaceAll("Z", "")), 10000)) ) {
                                iThingsAction++;
                                alTotalList.get(iRow1).put(Constants.HTTP_request_time, "");
                            }
                        }
                    }
                    if ( iThingsAction == 3 ) {
                        util.setShowToast(act, util.getString(act, R.string.MSG867), Toast.LENGTH_SHORT);
                        iThingsAction = 0;
                    }
                    setHomeHubStateList();
                }
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                if ( sERR_CODE.equals("401") ) {
                    if ( scheduledFuture != null ) {
                        scheduledFuture.cancel(false);
                    }
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    if ( scheduledFuture != null ) {
                        scheduledFuture.cancel(false);
                    }
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                    //                } else {
                    //                     customDialog.MsgAlert(act,Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            //             customDialog.MsgAlert(act,Constants.MSG807);
        }

        bPollingPause = bActStop;
    }

    /**
     * <PRE>
     * 1. MethodName: send_G_devices
     * 2. ClassName :
     * 3. Comment   : [Send][GET]장치 리스트 조회(회원의 장치 목록을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_G_devices() {

        try {
            HttpSend httpSend;

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

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

                    result_G_devices(result);
                }
            });
            if ( scheduledFuture != null ) {
                scheduledFuture.cancel(false);
            }
            alTotalList.clear();
            swipeRefreshLayout.setVisibility(View.GONE);
            httpSend.G_devices();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_G_devices
     * 2. ClassName :
     * 3. Comment   : [Result][GET]장치 리스트 조회(회원의 장치 목록을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_G_devices(Response rpResult) {

        loading = false;
        try {
            if ( rpResult.getStatusCode() == 200 ) {
                util.getTextView(toolbar, R.id.tvToolbarTitle2).setText("");
                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(rpResult.getContent());
                if ( alList.size() > 0 ) {
                    util.getTextView(toolbar, R.id.tvToolbarTitle2).setText(alList.size() + "");
                    for ( int iRow = 0; iRow < alList.size(); iRow++ ) {
                        HashMap<String, Object> hmTempDevice = new HashMap<String, Object>();
                        hmTempDevice = alList.get(iRow);
                        alTotalList.add(hmTempDevice);
                    }
                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    alTotalList.add(hmTemp);
                }
                setHomeHubStateAll();
                bPollingPause = bActStop;
                swipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_P_devices_device_id_nodes_node_id_commands
     * 2. ClassName :
     * 3. Comment   : [Send][POST]노드(커맨드클래스) 제어 명령 실행(노드(커맨드클래스) 제어 명령을 실행한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_P_devices_device_id_nodes_node_id_commands() {

        try {
            HttpSend httpSend;

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

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

                    result_P_devices_device_id_nodes_node_id_commands(result);
                }
            });
            httpSend.P_devices_device_id_nodes_node_id_commands(sCall_HTTP_device_id, sCall_HTTP_node_id, sCall_HTTP_request_value);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_P_devices_device_id_nodes_node_id_commands
     * 2. ClassName :
     * 3. Comment   : [Result][POST]노드(커맨드클래스) 제어 명령 실행(노드(커맨드클래스) 제어 명령을 실행한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_P_devices_device_id_nodes_node_id_commands(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                String sResultHTTP_device_id = util.null2string(joResult.get(Constants.HTTP_device_id));
                String sResultHTTP_node_id = util.null2string(joResult.get(Constants.HTTP_node_id));
                String sResultHTTP_request_time = util.null2string(joResult.get(Constants.HTTP_request_time));
                for ( int iRow = 0; iRow < alTotalList.size(); iRow++ ) {

                    String sHTTP_device_id = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_device_id));
                    String sHTTP_node_id = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_node_id));
                    if ( sResultHTTP_device_id.equals(sHTTP_device_id) && sResultHTTP_node_id.equals(sHTTP_node_id) ) {
                        alTotalList.get(iRow).put(Constants.HTTP_request_time, sResultHTTP_request_time);
                        break;
                    }
                }
                setHomeHubStateList();
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                if ( sERR_CODE.equals("401") ) {
                    customDialog.MsgAlert(act, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(act, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(act, Constants.MSG807);
        }
    }

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {

            case Constants.MSG998:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                } else {
                    act.onBackPressed();
                }
                break;
            default:
                break;
        }
    }

    private void MsgAlertList(ArrayList<HashMap<String, Object>> alList) {

        try {
            dialog_list_builder = new Dialog_Custom_List.Builder(act);
            dialog_list_builder.setList(alList);
            dialog_list_builder.setPositiveButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                    Dlog.v("which = " + which);
                    switch (which) {
                        case 1:
                            break;
                        case 2:
                            break;
                        case 3:
                            util.getView(toolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            util.getView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            dataAdapter.setListCheck(true);
                            dataAdapter.notifyDataSetChanged();
                            setRefresh(false);
                            break;
                        case 4:
                            break;
                        case 5:
                            break;
                        case 6:
                            onListReload();
                            break;
                        case 7:
                            break;
                        case 8:
                            break;
                        case 9:
                            Things_Device_Add();
                            break;
                        case 10:
                            break;
                        case 11:
                            break;
                        case 12:
                            break;
                        case 15:
                            break;
                        case 16:
                            break;
                    }
                }
            });
            dialog_list_builder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

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

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

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

    @Override public void onListReload() {

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

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

        if ( iCallType == 0 ) {
            //추가하기
            Things_Device_Add();
        } else if ( iCallType == 1 ) {
            String sHTTP_cmdcls_code = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_cmdcls_code));
            util.callBtnGoogleAnalytics(sActName, "ViewDetail_Things", sHTTP_cmdcls_code);
            // 상세보기
            String sHTTP_device_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_device_id));
            String sHTTP_node_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_node_id));
            intent = new Intent(act, Things_Detail.class);
            intent.putExtra(Constants.EXTRA_DEVICE_ID, sHTTP_device_id);
            intent.putExtra(Constants.EXTRA_NODE_ID, sHTTP_node_id);
            util.callActivityForResult(act, intent, Constants.ACT_THINGS_DETAIL);
        } else if ( iCallType == 2 ) {
            // 삭제하기
            String sHTTP_group_name = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_group_name));
            String sHTTP_device_name = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_device_name));
            String sHTTP_device_model_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_device_model_id));
            String sHTTP_device_mf_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_device_mf_id));
            String sDEVICE_DESC = util.getString(act, R.string.layout_things_device_add_07);

            String sGroupDevice = "";
            if ( !sHTTP_group_name.equals("") ) {
                for ( int iRow = 0; iRow < alTotalList.size() - 1; iRow++ ) {
                    if ( iRow != iPosition ) {
                        String sTempHTTP_device_name = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_device_name));
                        String sTempHTTP_group_name = util.null2string(alTotalList.get(iRow).get(Constants.HTTP_group_name));

                        if ( sHTTP_group_name.equals(sTempHTTP_group_name) ) {
                            sGroupDevice += (sGroupDevice.equals("") ? "" : ", ") + sTempHTTP_device_name;
                        }
                    }
                }
            }
            if ( !sGroupDevice.equals("") ) {
                sGroupDevice = util.getString(act, R.string.layout_things_device_del_01_05) + sGroupDevice + util.getString(act, R.string.layout_things_device_del_01_06);
            }

            intent = new Intent(act, Things_Device_Del_01.class);
            intent.putExtra(Constants.EXTRA_DEVICE_NAME, sHTTP_device_name);
            intent.putExtra(Constants.EXTRA_GROUP_DEVICE, sGroupDevice);
            if ( sHTTP_device_model_id.equals("HY-11-10A") && sHTTP_device_mf_id.equals("TimeValve") ) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_01));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_04));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_01_smartgasvalve);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_01_smartgasvalve_wait);
            } else if ( sHTTP_device_model_id.equals("SPD-01") && sHTTP_device_mf_id.equals("LGU+") ) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_05));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_02));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_05));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_02_iotplug);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_02_iotplug_wait);
            } else if ( sHTTP_device_model_id.equals("ZL7261KR-5") && sHTTP_device_mf_id.equals("VisionSecurity") ) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_07));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_02));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_06));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_03_smartplug);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_03_smartplug_wait);
            } else if ( sHTTP_device_model_id.equals("ZP3111") && sHTTP_device_mf_id.equals("VisionSecurity") ) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_09));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_08));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_04_mutisensor_motion);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_04_mutisensor_motion_wait);
            } else if ( sHTTP_device_model_id.equals("ZS5101") && sHTTP_device_mf_id.equals("VisionSecurity") ) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_11));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_10));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_05_shocksensor);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_05_shocksensor_wait);
            } else if ( sHTTP_device_model_id.equals("ZD211x") && sHTTP_device_mf_id.equals("VisionSecurity") ) {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_11));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_03));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_12));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_06_mutisensor_door);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_06_mutisensor_door_wait);
            } else {
                intent.putExtra(Constants.EXTRA_COMPANY_NAME, util.getString(act, R.string.layout_things_device_add_15));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC, util.getString(act, R.string.layout_things_device_add_del_13));
                intent.putExtra(Constants.EXTRA_DEVICE_DESC1, util.getString(act, R.string.layout_things_device_add_del_15));
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_00_zwave);
                intent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_00_zwave_wait);
            }
            util.callActivityForResultNoAnim(act, intent, Constants.ACT_THINGS_DEVICE_DEL_01);
        } else if ( iCallType == 3 ) {
            // 실행하기
            sCall_HTTP_request_value = dataAdapter.getHTTP_Value();
            sCall_HTTP_device_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_device_id));
            sCall_HTTP_node_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_node_id));
            sCall_HTTP_cmdcls_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_cmdcls_id));
            String sHTTP_content_value = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_content_value));
            String sHTTP_cmdcls_type_id = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_cmdcls_type_id));
            String sHTTP_cmdcls_code = util.null2string(alTotalList.get(iPosition).get(Constants.HTTP_cmdcls_code));
            //            int iCmdcls_Type = util.null2int(alTotalList.get(iPosition).get(Constants.HTTP_cmdcls_type_id));

            util.callBtnGoogleAnalytics(sActName, "Control_Things", sHTTP_cmdcls_code + "_1depth");

            Dlog.v("sCall_HTTP_request_value", sCall_HTTP_request_value);
            Dlog.v("sHTTP_content_value", sHTTP_content_value);

            String sTempValue = util.getStringValues(act, "CMDCLS_TYPE_ID_" + sHTTP_cmdcls_type_id + "_" + sCall_HTTP_request_value);

            if ( sCall_HTTP_request_value.equals(sHTTP_content_value) ) {
                util.setShowToast(act, util.getString(act, R.string.MSG899).replaceAll("\\'컨텐츠밸류\\'", sTempValue), Toast.LENGTH_SHORT);
                dataAdapter.notifyDataSetChanged();
                return;
            } else {
                util.setVibrator(100);
            }
            ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_WS_NODE_COMMAND), 10);
        }
    }
}
