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

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


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.broadcast.KneetMessageLocalBroadCast;
import com.ntels.onecable.admin.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.LogUtil;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.admin.HomehubBleStep1;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.ntels.onecable.admin.view.dialog.PushDialog;
import com.ntels.onecable.admin.view.things.ThingsNameChange;

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

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.ntels.onecable.admin.common.broadcast.DefaultLocalBroadCast.INTENT_NAME_TYPE;


public class Homehub extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

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

    private static final int MSG_COM_G_DEVICES = 1;
    private static final int MSG_COM_WS_DEVICE_COMMAND = 2;
    private static final int MSG_COM_WS_DEVICE_DELETE = 3;
    private static final int MSG_COM_WS_NODE_REGISTER = 4;
    private static final int MSG_COM_WS_FIRMWARE_UPGRADE = 5;
    private static final int MSG_COM_WS_SOFTWARE_UPGRADE = 6;


    private static final String HOMEHUB_DATETIME_FORMAT = "yyyy/MM/dd HH:mm:ss";

    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    @BindView(R.id.toolbar) Toolbar mToolbar;
    @BindView(R.id.tvConnStatus) TextView mConnStatus;
    @BindView(R.id.tvLastConnDatetime) TextView mLastConnStatus;
    @BindView(R.id.tvOnlineStatus) TextView mOnlineStatus;
    @BindView(R.id.tvLastOnlineDatetime) TextView mLastOnlineStatus;
    @BindView(R.id.tvFirmwareVersion) TextView mFirmwareVersion;
    @BindView(R.id.tvSoftwareVersion) TextView mSoftwareVersion;
    @BindView(R.id.tvModelName) TextView mModelName;
    @BindView(R.id.tvSerialNumber) TextView mSerialNumber;
    @BindView(R.id.btnNetworkSetting) Button mNetworkSetting;
    @BindView(R.id.btnFirmwareUpdate) Button mFirmwareUpdate;
    @BindView(R.id.btnSoftwareUpdate) Button mSoftwareUpdate;
    @BindView(R.id.llHomehubUpdate) LinearLayout mHomehubUpdateLayout;
    @BindView(R.id.tvHomehubUpdate) TextView mHomehubUpdateText;
    @BindView(R.id.btnHomehubUpdate) TextView mHomehubUpdateButton;
    /*통신 관련*/
    private int mType = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean mLoading = false;
    //  private WebSocketService webSocketService;
    private boolean isBound = false;
    private String mCameraSn = "";
    private String mSelectDeviceId = "";
    private String mSelectDeviceName = "";
    private boolean mIsReload = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = Homehub.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        setIsWebSocket(true);

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

        ButterKnife.bind(this);

        if (null != getIntent()) {
            mSelectDeviceId = getIntent().getStringExtra(Constants.EXTRA_DEVICE_ID);
        }

        setToolbar();
        displayListView();

        /*boolean isHiddenEnable = true;
        if (isHiddenEnable) {
            mUtil.getView(mActivity, R.id.llModelName).setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    AlertDialog.Builder alert = new AlertDialog.Builder(mActivity);
                    alert.setTitle("카메라 등록");
                    alert.setMessage("카메라번호-유저번호");
                    final EditText number = new EditText(mActivity);
                    number.setHint("ex) 07077775021-07077775028");
                    alert.setView(number);
                    alert.setPositiveButton("확인", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mCameraSn = number.getText().toString();
                            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_NODE_REGISTER), 10);
                            dialog.dismiss();
                        }
                    });
                    alert.setNegativeButton("취소", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    alert.show();
                    return false;
                }
            });
        }*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_THINGS_NAME_CHANGE:
                    mIsReload = true;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES), Constants.HANDLER_DELAY_MILLIS);
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                mActivity.setResult(RESULT_CANCELED, new Intent());
                finish();
            }
        }
    }

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(Constants.EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);

                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                LogUtil.i(TAG, "websocket message mType : " + messageType);

                switch (messageType) {
                    case Constants.WEBSOCKET_TYPE_DEVICE_DELETE:
                        resultWsDeviceDelete(jsonObject);
                        break;
                    case Constants.WEBSOCKET_TYPE_DEVICE_COMMAND:
                        resultWsDeviceCommand(jsonObject);
                        break;
//                    case Constants.WEBSOCKET_TYPE_FIRMWARE_UPGRADE:
//                        resultWsFirmwareUpgradeCommand(jsonObject);
//                        break;
//                    case Constants.WEBSOCKET_TYPE_FIRMWARE_UPGRADE_RESULT:
//                        notificationWsFirmwareUpgradeResult(jsonObject);
//                        break;
//                    case Constants.WEBSOCKET_TYPE_SOFTWARE_UPGRADE:
//                        resultWsSoftwareUpgradeCommand(jsonObject);
//                        break;
//                    case Constants.WEBSOCKET_TYPE_SOFTWARE_UPGRADE_RESULT:
//                        notificationWsSoftwareUpgradeResult(jsonObject);
//                        break;
                    default:
                        break;
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {

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

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

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

        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setText(mAppConfig.getHomehubDeviceName(mSelectDeviceId));

        setHomeHubState();
    }

    /**
     * 홈허브 상태에 따라 UI display.
     */
    private void setHomeHubState() {

        if (mUtil.null2string(mAppConfig.getDevicesList(mSelectDeviceId).get(Constants.KEY_DEVICE_CONN)).equalsIgnoreCase("connect")) {
            mConnStatus.setText(getString(R.string.layout_homehub_02));
            mLastConnStatus.setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.llState_Online).setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.llState_Offline).setVisibility(View.GONE);
        } else {
            String deviceConnLastDatetime = mAppConfig.getsSelect_CtrtGroup_Homehub_Mqtt_Online_Last_Datetime();
            mConnStatus.setText(getString(R.string.layout_homehub_03));
            mConnStatus.setTextColor(getResources().getColor(R.color.color_text_07));
            if (!"".equals(deviceConnLastDatetime)) {
                mLastConnStatus.setVisibility(View.VISIBLE);
                mLastConnStatus.setText(mUtil.UTCtoLocal5(HOMEHUB_DATETIME_FORMAT, deviceConnLastDatetime));
            } else {
                mLastConnStatus.setVisibility(View.GONE);
            }
//            mUtil.getView(mActivity, R.id.llState_Online).setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.llState_Offline).setVisibility(View.VISIBLE);
        }

        if (mUtil.null2string(mAppConfig.getDevicesList(mSelectDeviceId).get(Constants.KEY_DEVICE_ONLINE)).equalsIgnoreCase("ON")) {
            mOnlineStatus.setText(getString(R.string.layout_homehub_02));
            mLastOnlineStatus.setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.llState_Dongle_Online).setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.llState_Dongle_Offline).setVisibility(View.GONE);
        } else {
            String deviceOnlineLastDatetime = mAppConfig.getsSelect_CtrtGroup_Homehub_Dongle_Online_Last_Datetime();
            mOnlineStatus.setText(getString(R.string.layout_homehub_03));
            mOnlineStatus.setTextColor(getResources().getColor(R.color.color_text_07));
            if (!"".equals(deviceOnlineLastDatetime)) {
                mLastOnlineStatus.setVisibility(View.VISIBLE);
                mLastOnlineStatus.setText(mUtil.UTCtoLocal5(HOMEHUB_DATETIME_FORMAT, deviceOnlineLastDatetime));
//                mUtil.getTextView(mActivity, R.id.tvRecentDate).setVisibility(View.VISIBLE);
//                mUtil.getTextView(mActivity, R.id.tvRecentDate).setText(mActivity.getString(R.string.layout_homehub_15,
//                        mUtil.UTCtoLocal5(mAppConfig.getsSelect_CtrtGroup_Homehub_Dongle_Online_Last_Datetime())));
            } else {
                mLastOnlineStatus.setVisibility(View.GONE);
//                mUtil.getTextView(mActivity, R.id.tvRecentDate).setVisibility(View.GONE);
            }

//            mUtil.getView(mActivity, R.id.llState_Dongle_Online).setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.llState_Dongle_Offline).setVisibility(View.VISIBLE);
        }
    }

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

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

                if (!mLoading) {
                    mLoading = true;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES), Constants.HANDLER_DELAY_MILLIS);
                }
            }
        });
        setDisp();
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES), Constants.HANDLER_DELAY_MILLIS);
    }

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

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

        if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
            mUtil.getTextView(mToolbar, R.id.btnToolbarModify).setVisibility(View.VISIBLE);
            mUtil.getTextView(mToolbar, R.id.btnToolbarModify).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mIntent = new Intent(mActivity, ThingsNameChange.class);
                    mIntent.putExtra(Constants.EXTRA_DEVICE_ID, mSelectDeviceId);
                    mIntent.putExtra(Constants.EXTRA_DEVICE_NAME, mSelectDeviceName);
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_NAME_CHANGE);
                }
            });
            mNetworkSetting.setVisibility(View.VISIBLE);
//            mFirmwareUpdate.setVisibility(View.VISIBLE);
//            mSoftwareUpdate.setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.llKeyChange).setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.llHomehubDelete).setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.vLastDivider).setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.vLast_Section).setVisibility(View.VISIBLE);
        } else {
            mUtil.getTextView(mToolbar, R.id.btnToolbarModify).setVisibility(View.GONE);
            mNetworkSetting.setVisibility(View.GONE);
//            mFirmwareUpdate.setVisibility(View.GONE);
//            mSoftwareUpdate.setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.llKeyChange).setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.llHomehubDelete).setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.vLastDivider).setVisibility(View.GONE);
//            mUtil.getView(mActivity, R.id.vLast_Section).setVisibility(View.GONE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @OnClick({R.id.llBtn1, R.id.btnNetworkSetting, /*R.id.btnFirmwareUpdate, R.id.btnSoftwareUpdate,*/ R.id.btnHomehubUpdate})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                break;
            case R.id.btnNetworkSetting:
                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

//                if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
////                    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
//                }
                if (null == bluetoothAdapter) {
                    // TODO: 2017-05-17 혹시 블루투스 지원을 안하면?
                } else {
                    if (!bluetoothAdapter.isEnabled()) {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG930);
                        return;
                    } else {
                        Intent intent = new Intent(mActivity, HomehubBleStep1.class);
                        mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOMEHUB_BLE_STEP1);
                    }
                }
                break;
            /*case R.id.btnFirmwareUpdate: {
                Intent intent = new Intent(mActivity, HomehubUpdate.class);
                intent.putExtra(Constants.EXTRA_DEVICE_ID, mSelectDeviceId);
                intent.putExtra(Constants.EXTRA_CALL_TYPE, Constants.HOMEHUB_FIRMWARE_UPDATE);
                mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOMEHUB_UPDATE);

//                mFirmwareUpdate.setEnabled(false);
//                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_FIRMWARE_UPGRADE), 10);
                break;
            }
            case R.id.btnSoftwareUpdate: {
                Intent intent = new Intent(mActivity, HomehubUpdate.class);
                intent.putExtra(Constants.EXTRA_DEVICE_ID, mSelectDeviceId);
                intent.putExtra(Constants.EXTRA_CALL_TYPE, Constants.HOMEHUB_SOFTWARE_UPDATE);
                mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOMEHUB_UPDATE);

//                mSoftwareUpdate.setEnabled(false);
//                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_SOFTWARE_UPGRADE), 10);
                break;
            }*/
            case R.id.btnHomehubUpdate:
                if (Constants.HOMEHUB_FIRMWARE_UPDATE == Integer.parseInt(view.getTag().toString())) {
                    Intent intent = new Intent(mActivity, HomehubUpdate.class);
                    intent.putExtra(Constants.EXTRA_DEVICE_ID, mSelectDeviceId);
                    intent.putExtra(Constants.EXTRA_CALL_TYPE, Constants.HOMEHUB_FIRMWARE_UPDATE);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOMEHUB_UPDATE);
                } else if (Constants.HOMEHUB_SOFTWARE_UPDATE == Integer.parseInt(view.getTag().toString())) {
                    Intent intent = new Intent(mActivity, HomehubUpdate.class);
                    intent.putExtra(Constants.EXTRA_DEVICE_ID, mSelectDeviceId);
                    intent.putExtra(Constants.EXTRA_CALL_TYPE, Constants.HOMEHUB_SOFTWARE_UPDATE);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOMEHUB_UPDATE);
                } else {

                }
                break;
            /*case R.id.btnKeyChange:
                mIntent = new Intent(mActivity, HomehubPasswordChange.class);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_HOMEHUB_PASSWORD_CHANGE);
                break;
            case R.id.btnHomehubDelete:
                mCustomDialog.msgAlert(mActivity, Constants.MSG904);
                break;*/
            default:
                break;
        }
    }

    /**
     * 서비스허브에 노드 등록 요청.
     */
    private void sendWsNodeRegister() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_NODE_REGISTER);
        sendParams.put(Constants.KEY_DEVICE_ID,
                mAppConfig.getSelectHomehubDeviceId());
        sendParams.put(Constants.KEY_NODE_MANUFACTURER, "NTels");
        sendParams.put(Constants.KEY_NODE_MODEL_NUMBER, "OnVifCamera");
        sendParams.put(Constants.KEY_NODE_SERIAL_NUMBER, mCameraSn);
        sendParams.put(Constants.KEY_NODE_PROFILE_VERSION, "v3");
        sendParams.put(Constants.KEY_REQUEST_ID,
                mAppConfig.getSelectServicehubRequestId());

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

    /**
     * <pre>
     * 홈허브 목록 조회(디바이스 아이디를 보내면 해당 홈허브의 정보만 조회) 요청.
     * </pre>
     */
    private void sendGetDevicesDetail() {
        try {
            HttpSend httpSend;

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

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

                    resultGetDevicesDetail(result);
                }
            });
            httpSend.getHomehubList(mSelectDeviceId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendGetDevicesDetail()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultGetDevicesDetail(Response response) {

        try {
            if (response.getStatusCode() == 200) {
                String deviceConn = "";
                String deviceConnLastDatetime = "";
                String deviceOnline = "";
                String deviceOnlineLastDatetime = "";
                String deviceUserName = "";
                String deviceName = "";
                JSONObject joResult = new JSONArray(response.getContent()).getJSONObject(0);
                if (joResult.has(Constants.KEY_DEVICE_CONN)) {
                    deviceConn = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_CONN));
                }
                if (joResult.has(Constants.KEY_DEVICE_CONN_LAST_DATETIME)) {
                    deviceConnLastDatetime = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_CONN_LAST_DATETIME));
                }
                if (joResult.has(Constants.KEY_DEVICE_ONLINE_LAST_DATETIME)) {
                    deviceOnlineLastDatetime = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ONLINE_LAST_DATETIME));
                }
                if (joResult.has(Constants.KEY_DEVICE_ONLINE)) {
                    deviceOnline = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ONLINE));
                }
                if (joResult.has(Constants.KEY_PRD_USER_NAME)) {
                    deviceUserName = mUtil.null2string(joResult.get(Constants.KEY_PRD_USER_NAME));
                }
                if (joResult.has(Constants.KEY_PRD_NAME)) {
                    deviceName = mUtil.null2string(joResult.get(Constants.KEY_PRD_NAME));
                }

                mSelectDeviceName = !"".equals(deviceUserName) ? deviceUserName : deviceName;
                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setText(mSelectDeviceName);

                String deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
//                String deviceKey = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_KEY));

                String preOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);
//                mAppConfig.setsSelect_Homegrp_Homehub_Conn_State(deviceConn);
//                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State(deviceOnline);

                mAppConfig.getDevicesList(deviceId).put(Constants.KEY_DEVICE_CONN, deviceConn);
                mAppConfig.getDevicesList(deviceId).put(Constants.KEY_DEVICE_ONLINE, deviceOnline);
                mAppConfig.setsSelect_CtrtGroup_Homehub_Dongle_Online_Last_Datetime(deviceOnlineLastDatetime);
                mAppConfig.setsSelect_CtrtGroup_Homehub_Mqtt_Online_Last_Datetime(deviceConnLastDatetime);
                mAppConfig.setSelectHomehubDeviceId(deviceId);
//                mAppConfig.setSelectHomehubDeviceKey(deviceKey);
                String currentOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);
                if (!preOnlineStatus.equals(currentOnlineStatus)) {
                    //상태가 변경되었을때만 브로드캐스트를 날려준다
                    Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                    intent.putExtra(KneetMessageLocalBroadCast.INTENT_NAME_TYPE, KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE);
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                }

                setHomeHubState();
                // 현재/최신 펌웨어, 소프트웨어 버전 display.
                String currentFirmwareVer = mUtil.null2string(joResult.get(Constants.KEY_FIRMWARE_VERSION));
                String recentFirmwareVer = mUtil.null2string(joResult.get(Constants.KEY_LAST_FIRMWARE_VERSION));
                String currentSoftwareVer = mUtil.null2string(joResult.get(Constants.KEY_SOFTWARE_VERSION));
                String recentSoftwareVer = mUtil.null2string(joResult.get(Constants.KEY_LAST_SOFTWARE_VERSION));
                mFirmwareVersion.setText(getString(R.string.layout_homehub_08, currentFirmwareVer, recentFirmwareVer));
                mSoftwareVersion.setText(getString(R.string.layout_homehub_08, currentSoftwareVer, recentSoftwareVer));

                if (Constants.GRADE_CODE_MAS.equals(mAppConfig.getCtrtGroupGradeCode())) {
                    if (currentFirmwareVer.equals(recentFirmwareVer) && currentSoftwareVer.equals(recentSoftwareVer)) {
                        // 펌웨어/소프트웨어 현재 버전이 최신버전이면 업데이트 레이아웃 보여주지 않음.
                        mHomehubUpdateLayout.setVisibility(View.GONE);
                    } else {
                        // 펌웨어, 소프트웨어 모두 업데이트가 있을 시 펌웨어 업데이트 먼저 진행.
                        if (!currentFirmwareVer.equals(recentFirmwareVer)) {
                            mHomehubUpdateText.setText(getString(R.string.layout_homehub_13, getString(R.string.layout_homehub_07),
                                    recentFirmwareVer));
                            mHomehubUpdateButton.setTag(Constants.HOMEHUB_FIRMWARE_UPDATE);
                        } else if (!currentSoftwareVer.equals(recentSoftwareVer)) {
                            mHomehubUpdateText.setText(getString(R.string.layout_homehub_13, getString(R.string.layout_homehub_09),
                                    recentSoftwareVer));
                            mHomehubUpdateButton.setTag(Constants.HOMEHUB_SOFTWARE_UPDATE);
                        } else {

                        }
                        mHomehubUpdateLayout.setVisibility(View.VISIBLE);
                    }
                }

                String deviceModelName = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_MODEL_ID));
                mModelName.setText(deviceModelName);
                String deviceSn = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_SN));
                mSerialNumber.setText(deviceSn);

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

                if (resultCode.equals("401")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    if (resultCode.equals("400-404")) {
                        mAppConfig.getDevicesList(mSelectDeviceId).put(Constants.KEY_DEVICE_ONLINE, "");
                        //상태가 변경되었을때만 브로드캐스트를 날려준다
                        Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                        intent.putExtra(INTENT_NAME_TYPE, KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE);
                        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    @Override
    public void onBackPressed() {

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

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

        switch (msgId) {
            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), 10);
                }
                break;
            case Constants.MSG904:
                if (btnResult == 1) {
                    if (mUtil.null2string(mAppConfig.getDevicesList(mSelectDeviceId).get(Constants.KEY_DEVICE_CONN)).equalsIgnoreCase
                            ("connect")) {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_COMMAND), 10);
                    } else {
                        // 홈허브가 disconnect상태일때는 profile_reset 커맨드를 보내지 않고 바로 삭제 요청한다.
                        resultWsDeviceCommand(null);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 서비스 허브에 디바이스 제어(프로필 리셋)를 요청한다.
     */
    private void sendWsDeviceCommand() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_DEVICE_COMMAND);
        sendParams.put(Constants.KEY_DEVICE_ID, mAppConfig.getSelectHomehubDeviceId());
        sendParams.put(Constants.KEY_COMMAND_TYPE, Constants.WEBSOCKET_COMM_TYPE_PROFILE_RESET);
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());

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

    /**
     * {@link #sendWsDeviceCommand()} 요청 결과.
     *
     * @param joResult 결과 data
     */
    private void resultWsDeviceCommand(JSONObject joResult) {

        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_WS_DEVICE_DELETE), 10);

        try {
            mUtil.getView(mActivity, R.id.llBtn1).setEnabled(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 서비스 허브에 등록된 홈허브 디바이스를 삭제한다.
     */
    private void sendWsDeviceDelete() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_DEVICE_DELETE);
        sendParams.put(Constants.KEY_DEVICE_ID,
                mAppConfig.getSelectHomehubDeviceId());
        sendParams.put(Constants.KEY_DEVICE_KEY,
                mAppConfig.getSelectHomehubDeviceKey());
        sendParams.put(Constants.KEY_REQUEST_ID,
                mAppConfig.getSelectServicehubRequestId());

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

    /**
     * {@link #sendWsDeviceDelete()} 요청 결과.
     *
     * @param joResult 결과 data
     *
     * @exception JSONException json parsing exception
     */
    private void resultWsDeviceDelete(JSONObject joResult) throws JSONException {
        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
        String resultMsg = "";
        String myDeviceId = mAppConfig.getSelectHomehubDeviceId();
        String deleteDeviceId = joResult.getString(Constants.KEY_DEVICE_ID);
        if (joResult.has(Constants.KEY_RESULT_MSG)) {
            resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
        }
        if (resultCode.equals("00") && myDeviceId.equalsIgnoreCase(deleteDeviceId)) {
            mAppConfig.setSelectHomehubDeviceId("");
            mAppConfig.setSelectHomehubDeviceKey("");
//            mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State("");
//            mAppConfig.setsSelect_Homegrp_Homehub_Conn_State("");
            mAppConfig.getDevicesList(mSelectDeviceId).put(Constants.KEY_DEVICE_CONN, "");
            mAppConfig.getDevicesList(mSelectDeviceId).put(Constants.KEY_DEVICE_ONLINE, "");

            mIntent = new Intent();
            mIntent.putExtra(Constants.EXTRA_RELOAD_FLAG, true);
            mActivity.setResult(RESULT_OK, mIntent);
            finish();
        } else {
            mUtil.setShowToast(mActivity, resultMsg, Toast.LENGTH_SHORT);
        }
    }
//
//    /**
//     * 서비스 허브에 펌웨어 업그레이드를 요청한다.
//     */
//    private void sendWsFirmwareUpgradeCommand() {
//        HashMap<String, Object> sendParams = new HashMap<>();
//        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_FIRMWARE_UPGRADE);
//        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
//        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
//        sendParams.put(Constants.KEY_DEVICE_ID, mSelectDeviceId);
//        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());
//
//        getWebSocketService().send(Constants.WEBSOCKET_SEND_FIRMWARE_UPGRADE, sendParams);
//    }
//
//    /**
//     * {@link #sendWsFirmwareUpgradeCommand() 노드 제어} 요청 결과.
//     *
//     * @param joResult 결과 json object
//     *
//     * @exception JSONException json parsing exception
//     */
//    private void resultWsFirmwareUpgradeCommand(JSONObject joResult) throws JSONException {
//
//        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//        if (resultCode.equals("00")) {
////            mCommandId = joResult.getString(Constants.KEY_COMMAND_ID);
//        } else {
////            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
////            mCustomDialog.msgAlert(mActivity, Constants.MSG933);
//            Dlog.v(joResult.toString());
//            String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
//
//            if ("401".equals(resultCode)) {
//                mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
//            } else if ("401-106".equals(resultCode)) {
//                mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
//            } else {
//                mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
//            }
//        }
//    }
//
//    /**
//     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 결과를 푸쉬받는다.
//     *
//     * @param joResult : 결과 json object
//     *
//     * @exception JSONException : json parsing exception
//     */
//    private void notificationWsFirmwareUpgradeResult(JSONObject joResult) throws JSONException {
//        try {
//
//            dialog_dismiss();
//            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//            if (resultCode.equals("00")) {
//
//                mFirmwareUpdate.setEnabled(true);
//                mFirmwareUpdate.setVisibility(View.GONE);
//                mCustomDialog.msgAlert(mActivity, Constants.MSG932);
//            } else {
//                Dlog.v(joResult.toString());
//                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
//
//                if ("401".equals(resultCode)) {
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
//                } else if ("401-106".equals(resultCode)) {
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
//                } else {
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
//                }
//            }
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
//        }
////        try {
////            mUtil.getView(mActivity, R.id.llBtn2).setEnabled(true);
////        } catch (Exception ex) {
////            ex.printStackTrace();
////        }
//    }

//    /**
//     * 서비스 허브에 소프트웨어 업그레이드를 요청한다.
//     */
//    private void sendWsSoftwareUpgradeCommand() {
//        HashMap<String, Object> sendParams = new HashMap<>();
//        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_SOFTWARE_UPGRADE);
//        sendParams.put(Constants.KEY_CUST_ID, mAppConfig.getCustId());
//        sendParams.put(Constants.KEY_CTRT_GRP_ID, mAppConfig.getCtrtGroupId());
//        sendParams.put(Constants.KEY_DEVICE_ID, mSelectDeviceId);
//        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());
//
//        getWebSocketService().send(Constants.WEBSOCKET_SEND_SOFTWARE_UPGRADE, sendParams);
//    }
//
//    /**
//     * {@link #sendWsFirmwareUpgradeCommand() 노드 제어} 요청 결과.
//     *
//     * @param joResult 결과 json object
//     *
//     * @exception JSONException json parsing exception
//     */
//    private void resultWsSoftwareUpgradeCommand(JSONObject joResult) throws JSONException {
//
//        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//        if (resultCode.equals("00")) {
////            mCommandId = joResult.getString(Constants.KEY_COMMAND_ID);
//        } else {
////            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG836), Toast.LENGTH_SHORT);
////            mCustomDialog.msgAlert(mActivity, Constants.MSG933);
//            Dlog.v(joResult.toString());
//            String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
//
//            if ("401".equals(resultCode)) {
//                mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
//            } else if ("401-106".equals(resultCode)) {
//                mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
//            } else {
//                mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
//            }
//        }
//    }
//
//    /**
//     * 서비스 허브에 디바이스 제어(노드 언페어링 중지) 결과를 푸쉬받는다.
//     *
//     * @param joResult : 결과 json object
//     *
//     * @exception JSONException : json parsing exception
//     */
//    private void notificationWsSoftwareUpgradeResult(JSONObject joResult) throws JSONException {
//        try {
//
//            dialog_dismiss();
//            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//            if (resultCode.equals("00")) {
//
//                mSoftwareUpdate.setEnabled(true);
//                mSoftwareUpdate.setVisibility(View.GONE);
//                mCustomDialog.msgAlert(mActivity, Constants.MSG932);
//            } else {
//                Dlog.v(joResult.toString());
//                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
//
//                if ("401".equals(resultCode)) {
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
//                } else if ("401-106".equals(resultCode)) {
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
//                } else {
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
//                }
//            }
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
//        }
////        try {
////            mUtil.getView(mActivity, R.id.llBtn2).setEnabled(true);
////        } catch (Exception ex) {
////            ex.printStackTrace();
////        }
//    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICES:
                    sendGetDevicesDetail();
                    break;
                case MSG_COM_WS_DEVICE_COMMAND:
                    sendWsDeviceCommand();
                    break;
                case MSG_COM_WS_DEVICE_DELETE:
                    sendWsDeviceDelete();
                    break;
                case MSG_COM_WS_NODE_REGISTER:
                    sendWsNodeRegister();
                    break;
//                case MSG_COM_WS_SOFTWARE_UPGRADE:
//                    sendWsSoftwareUpgradeCommand();
//                    break;
//                case MSG_COM_WS_FIRMWARE_UPGRADE:
//                    sendWsFirmwareUpgradeCommand();
//                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
