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

package com.ntels.onecable.view;

import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.broadcast.KneetMessageLocalBroadCast;
import com.ntels.onecable.common.c_interface.MainInterface;
import com.ntels.onecable.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.common.db.DatabaseOpenHelper;
import com.ntels.onecable.common.db.SqlManager;
import com.ntels.onecable.common.handler.BackPressCloseHandler;
import com.ntels.onecable.common.http.HttpSend;
import com.ntels.onecable.common.http.Response;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.LogUtil;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.websocket.OnWebSocketResponse;
import com.ntels.onecable.common.websocket.WebSocketService;
import com.ntels.onecable.common.widget.CustomActionBarActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.homemember.FragmentHomeMember;
import com.ntels.onecable.view.invitation.InvitationList;
import com.ntels.onecable.view.mainmore.FragmentMainMore;
import com.ntels.onecable.view.mainmore.SettingPasswordChange;
import com.ntels.onecable.view.rules.FragmentRules;
import com.ntels.onecable.view.things.FragmentThings;
import com.ntels.onecable.view.things.ThingsHomehubGuide;

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

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;

import java.util.HashMap;

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

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

    private static final int MSG_MAIN_INIT = 1;
    private static final int MSG_COM_G_MEMBER_LOGOUT = 2;
    private static final int MSG_COM_G_MEMBER = 3;
    private static final int MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID = 4;
    private static final int MSG_COM_WS_DEVICE_ALIVE = 5;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private BackPressCloseHandler mBackPressCloseHandler;
    private AppConfig mAppConfig;
    private SqlManager mSqlManager = new SqlManager();
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private Activity mActivity;
    private int mType = 0;
    private int mFragmentPosition = 0;
    private Fragment mFragment;
    private String mPushTypeCode = "";
    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;
    private OnWebSocketResponse webSocketResponse = new OnWebSocketResponse() {
        @Override
        public void onResponse(String result) {
            try {

                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                LogUtil.i(TAG, "websocket message mType : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if (jsonObject.has(Constants.KEY_RESULT_CODE)) {
                    resultCode = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_CODE));
                }
                if (jsonObject.has(Constants.KEY_RESULT_MSG)) {
                    resultMsg = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_MSG));
                }
                if (messageType.equals(Constants.WEBSOCKET_TYPE_DEVICE_CONTENT)) {
                    notificationWsDeviceContent(jsonObject);
                } else if (Constants.WEBSOCKET_TYPE_AUTH.equals(messageType)) {
                    if (mAppConfig.getbWebSocketAuth()) {
                        comHandler.sendEmptyMessageDelayed(MSG_COM_WS_DEVICE_ALIVE, Constants.HANDLER_DELAY_MILLIS);
                    }
                } else if (Constants.WEBSOCKET_TYPE_DEVICE_ALIVE.equals(messageType)) {
                    resultWsDeviceAlive(jsonObject);
                } else {
                    return;
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }

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

        }
    };
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtil.i(TAG, "onServiceConnected!!");
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            mWebSocketService = binder.getService();
            mWebSocketService.addWebSocketResponse(webSocketResponse);
            mIsBound = true;
        }

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

    @Override
    protected void onNewIntent(Intent saveIntent) {

        super.onNewIntent(saveIntent);
        if (null != saveIntent) {
            mPushTypeCode = "";
            mPushTypeCode = mUtil.null2string(saveIntent.getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
            Dlog.v(mPushTypeCode);

            if ("HOME_MEM_INV".equals(mPushTypeCode)) {
                //    홈 초대 받음
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("HOME_MEM_REF".equals(mPushTypeCode)) {
                //    초대했는데 거절 당할 시
            } else if ("HOME_MEM_BAN".equals(mPushTypeCode)) {
                LogUtil.i(TAG, "Main : HOME_MEM_BAN!!");
                //    홈 강퇴 받음
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("HOME_MEM_SEL".equals(mPushTypeCode)) {
                //    홈 자진 탈퇴 받음
            } else if ("HOME_DEL".equals(mPushTypeCode)) {
                //    홈 삭제
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("DVC_CER_REV".equals(mPushTypeCode)) {
                //    단말 인증 해지 됨
                onLogout();
            } else if ("MODE_CHG".equals(mPushTypeCode)) {
                //    홈 모드 변경 시
            } else if ("MODE_CHG_ERR".equals(mPushTypeCode)) {
                //    홈 모드 변경 시 일부 장치 제어 실패
            } else if ("RULE_EXC".equals(mPushTypeCode)) {
                //    규칙의 액션 결과
            } else if ("RULE_ERR".equals(mPushTypeCode)) {
                //    규칙 실패 누적으로 규칙 비 활성시킴
            } else if ("HOMEHUB_DEL".equals(mPushTypeCode)) {
                //    홈 허브가 삭제됨
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("DVC_OWN_CHG".equals(mPushTypeCode)) {
                //    장치 소유주 변경 알림
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("MEM_ALL_OUT".equals(mPushTypeCode)) {
                //    멤버 All out 시
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("MEM_ANY_IN".equals(mPushTypeCode)) {
                //    멤버 Any in 시
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("HOME_RELOAD".equals(mPushTypeCode)) {
                //    홈 멤버 정보 재조회 알림
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("LOGOUT".equals(mPushTypeCode)) {
                //    강제 로그아웃 시킴
                onLogout();
            }

            Boolean isTemp = saveIntent.getBooleanExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE, false);
            Dlog.v("isTemp", isTemp);
            if (mFragmentPosition == Constants.MENU_THINGS) {
                FragmentThings fragment = (FragmentThings) getSupportFragmentManager().findFragmentById(R.id.frame_container);
                fragment.setHomeHubStateAll();
            }
            if (mFragmentPosition == Constants.MENU_HOMEMEMBER) {
                FragmentHomeMember fragment = (FragmentHomeMember) getSupportFragmentManager().findFragmentById(R.id.frame_container);
                fragment.setHomeHubStateAll();
            }
            if (mFragmentPosition == Constants.MENU_RULES) {
                FragmentRules fragment = (FragmentRules) getSupportFragmentManager().findFragmentById(R.id.frame_container);
                fragment.setHomeHubStateAll();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = Main.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);
        mBackPressCloseHandler = new BackPressCloseHandler(this);

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            mActivity.getWindow().setStatusBarTextColor(getResources().getColor(R.color.color_text_01));
//        }
        Dlog.v("mAppConfig.getIntro()=" + mAppConfig.getIntro());

        Intent intent = new Intent(mActivity, WebSocketService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

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

        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_MAIN_INIT), Constants.HANDLER_DELAY_MILLIS);

        mAppConfig.setMain(true);
    }

    @Override
    protected void onResume() {
        LogUtil.i(TAG, "onResume()!!");

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

    @Override
    protected void onPause() {

        super.onPause();

        if (mWebSocketService != null) {
            if (mWebSocketService.isWebSocketConnected()) {
                mWebSocketService.webSocketDisconnect();
            }
        }
//        if (mIsBound) {
//            mWebSocketService.removeWebSocketResponse(webSocketResponse);
//            mWebSocketService.webSocketClose();
//            mActivity.unbindService(serviceConnection);
//            mIsBound = false;
//        }
    }

    /**
     * initialize.
     */
    private void setInit() {

        mUtil.getView(mActivity, R.id.llMainNavi1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llMainNavi2).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llMainNavi3).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llMainNavi4).setOnClickListener(this);
        displayView(Constants.MENU_THINGS);
        if (mAppConfig.getTemp_Password_Yn().equals("Y")) {
            mCustomDialog.msgAlert(mActivity, Constants.MSG892);
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llMainNavi1:
                displayView(Constants.MENU_THINGS);
                break;
            case R.id.llMainNavi2:
                displayView(Constants.MENU_RULES);
                break;
            case R.id.llMainNavi3:
                displayView(Constants.MENU_HOMEMEMBER);
                break;
            case R.id.llMainNavi4:
//                mIntent = new Intent(mActivity, FragmentMainMore.class);
//                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_MAIN_MORE,
//                        Constants.CHANGE_EVENT_BOTTOM_BOTTOM);
                displayView(Constants.MENU_MAINMORE);
                break;
            default:
                break;
        }
    }

    /**
     * 메뉴 탭 선택.
     *
     * @param view 선택된 메뉴
     */
    private void selectMainNavi(View view) {

        mUtil.getView(mActivity, R.id.llMainNavi1).setSelected(false);
        mUtil.getView(mActivity, R.id.llMainNavi2).setSelected(false);
        mUtil.getView(mActivity, R.id.llMainNavi3).setSelected(false);
        view.setSelected(true);
    }

    /**
     * UI display.
     *
     * @param position 보여줄 view index
     */
    private void displayView(int position) {

        switch (position) {
            case Constants.MENU_THINGS:
                LogUtil.i(TAG, "displayView : MENU_THINGS");
                selectMainNavi(mUtil.getView(mActivity, R.id.llMainNavi1));
                mFragment = new FragmentThings();
                break;
            case Constants.MENU_RULES:
                selectMainNavi(mUtil.getView(mActivity, R.id.llMainNavi2));
                mFragment = new FragmentRules();
                break;
            case Constants.MENU_HOMEMEMBER:
                selectMainNavi(mUtil.getView(mActivity, R.id.llMainNavi3));
                mFragment = new FragmentHomeMember();
                break;
            case Constants.MENU_MAINMORE:
                selectMainNavi(mUtil.getView(mActivity, R.id.llMainNavi4));
                mFragment = new FragmentMainMore();
                break;
            default:
                break;
        }
        if (mFragment != null) {
            FragmentManager fmBody = getSupportFragmentManager();
            FragmentTransaction ft = fmBody.beginTransaction();
            if (mFragmentPosition > position) {
                ft.setCustomAnimations(R.anim.left_in, R.anim.right_out);
            } else if (mFragmentPosition < position) {
                ft.setCustomAnimations(R.anim.right_in, R.anim.left_out);
            }
            ft.replace(R.id.frame_container, mFragment);
            ft.commit();
        }
        mFragmentPosition = position;
    }

    @Override
    protected void onDestroy() {

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

        if (mIsBound) {
            Dlog.v("onDestroy()11");
            mWebSocketService.removeWebSocketResponse(webSocketResponse);
            mWebSocketService.webSocketClose();
            mActivity.unbindService(serviceConnection);
            mIsBound = false;
        }
    }

    @Override
    public void setTitle(CharSequence title) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

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

        try {
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case Constants.ACT_LOGIN:
                        displayView(Constants.MENU_DASHBOARD);
                        break;
                    case Constants.ACT_INVITATION_LIST:
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(
                                MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
                        break;
                    case Constants.ACT_HOME_SELECT_POP:
                        displayView(Constants.MENU_DASHBOARD);
                        break;
                    case Constants.ACT_THINGS_GROUP_ADD:
                        break;
                    case Constants.ACT_THINGS_HOMEHUB_GUIDE:
                        if (mWebSocketService != null
                                && !mWebSocketService.isWebSocketConnected()) {
                            mWebSocketService.webSocketConnect();
                        }
                        Intent intent = new Intent(mActivity, HomeStart.class);
                        mUtil.callActivityForResultNoAnim(mActivity, intent,
                                Constants.ACT_HOME_START);
                        break;
                    case Constants.ACT_HOME_START:
                        mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                        break;
                    case Constants.ACT_MAIN_MORE:
                        displayView(mFragmentPosition);
                        break;
                    default:
                        mFragment = getSupportFragmentManager().findFragmentById(R.id.frame_container);
                        if (mFragment != null) {
                            mFragment.onActivityResult(requestCode, resultCode, data);
                        }
                        break;
                }
            } else {
                switch (requestCode) {
                    case Constants.ACT_HOME_START:
                        displayView(mFragmentPosition);
                        break;
                    case Constants.ACT_MAIN_MORE:
                        if (mAppConfig.getLogout()) {
                            mAppConfig.setLogout(false);
                            return;
                        }
                        displayView(mFragmentPosition);
                        break;
                    default:
                        mFragment = getSupportFragmentManager().findFragmentById(R.id.frame_container);
                        if (mFragment != null) {
                            mFragment.onActivityResult(requestCode, resultCode, data);
                        }
                        break;
                }
                if (mAppConfig.getGoErr()) {
                    setExit();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {

        Dlog.v("onBackPressed()");
        mBackPressCloseHandler.onBackPressed("setExit");
    }

    @Override
    public void onLogout() {

        Dlog.v("onLogout");
        comHandler.sendMessage(comHandler.obtainMessage(MSG_COM_G_MEMBER_LOGOUT));
    }

    @Override
    public void onHomehubStart() {

        Intent intent = new Intent(mActivity, ThingsHomehubGuide.class);
        mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_THINGS_HOMEHUB_GUIDE);
    }

    @Override
    public void onHomeMemberWidthdraw() {

        mCustomDialog.msgAlert(mActivity, Constants.MSG835, R.string.MSG_TITLE_002);
    }

    @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.MSG805:
                if (btnResult == 1) {
                    comHandler.sendMessage(comHandler.obtainMessage(MSG_COM_G_MEMBER_LOGOUT));
                }
                break;
            case Constants.MSG835:
                if (btnResult == 1) {
                    comHandler.sendMessage(comHandler.obtainMessage(
                            MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID));
                }
                break;
            case Constants.MSG892:
                mAppConfig.setTemp_Password_Yn("");
                mAppConfig.setLogin_Pass("");
                if (btnResult == 1) {
                    mIntent = new Intent(mActivity, SettingPasswordChange.class);
                    mIntent.putExtra(Constants.EXTRA_PASSWORD, mAppConfig.getLogin_Pass());
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent,
                            Constants.ACT_SETTING_PASSWORD_CHANGE);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 홈그룹 (자진) 탈퇴(일반 등급의 홈그룹 멤버를 홈그룹에서 자진 탈퇴 처리한다) 요청.
     */
    private void sendDeleteHomegrpMember() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

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

                    resultDeleteHomegrpMember(result);
                }
            });
            httpSend.D_homegrp_members_member_id();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈그룹 (자진) 탈퇴(일반 등급의 홈그룹 멤버를 홈그룹에서 자진 탈퇴 처리한다) 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultDeleteHomegrpMember(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));

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

    public void sendWsDeviceAlive() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_DEVICE_ALIVE);
        sendParams.put(Constants.KEY_DEVICE_ID,
                mAppConfig.getSelect_Homegrp_Homehub_Device_Id());
        sendParams.put(Constants.KEY_REQUEST_ID,
                mAppConfig.getiSelect_Servicehub_Request_Id());

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

    private void resultWsDeviceAlive(JSONObject joResult) throws JSONException {
        String deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        if (deviceId.equals(mAppConfig.getSelect_Homegrp_Homehub_Device_Id())) {
            String deviceConn = mUtil.null2string(joResult.get(
                    Constants.KEY_DEVICE_CONN));
            String deviceOnline = mUtil.null2string(joResult.get(
                    Constants.KEY_DEVICE_ONLINE));
            String connLastModifiedTime = mUtil.null2string(joResult.get(
                    Constants.KEY_CONN_LAST_MODIFIED_TIME));
            String onlineLastModifiedTime = mUtil.null2string(joResult.get(
                    Constants.KEY_ONLINE_LAST_MODIFIED_TIME));
            String preOnlineStatus = mAppConfig.getSelect_Homegrp_Homehub_Online_State();

            mAppConfig.setsSelect_Homegrp_Homehub_Conn_State(deviceConn);
            mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State(deviceOnline);

            String currentOnlineStatus = mAppConfig.getSelect_Homegrp_Homehub_Online_State();

            if (!currentOnlineStatus.equals(preOnlineStatus)) {
                //상태가 변경되었을때만 브로드캐스트를 날려준다
                Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                intent.putExtra(KneetMessageLocalBroadCast.INTENT_NAME_TYPE,
                        KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE);
                intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE,
                        true);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            }
        }
    }

    /**
     * 홈허브 장치 상태 정보를 푸쉬받는다(현재 홈그룹에 등록된 홈허브의 상태 정보).
     *
     * @param joResult : json data object
     *
     * @exception JSONException : json parsing exception
     */
    private void notificationWsDeviceContent(JSONObject joResult) throws JSONException {
        JSONObject contentValue = (JSONObject) joResult.get(Constants.KEY_CONTENT_VALUE);
        if (contentValue.has(Constants.KEY_ONLINE)) {
            String preOnlineStatus = mAppConfig.getSelect_Homegrp_Homehub_Online_State();
            String pushOnlineStatus = ((JSONObject)
                    joResult.get(Constants.KEY_CONTENT_VALUE))
                    .getString(Constants.KEY_ONLINE);
            String currentOnlineStatus = "";

            if ("ON".equalsIgnoreCase(pushOnlineStatus)) {
                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State("ON");
                mAppConfig.setsSelect_Homegrp_Homehub_Conn_State("connect");
            } else {
                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State("OFF");
                mAppConfig.setsSelect_Homegrp_Homehub_Conn_State("connect");
            }

            currentOnlineStatus = mAppConfig.getSelect_Homegrp_Homehub_Online_State();

            if (!currentOnlineStatus.equals(preOnlineStatus)) {
                //상태가 변경되었을때만 브로드캐스트를 날려준다
                Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                intent.putExtra(KneetMessageLocalBroadCast.INTENT_NAME_TYPE,
                        KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE);
                intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE,
                        true);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            }
        }
    }

    /**
     * <pre>
     * 멤버 자동 로그인 요청.
     * (인증 토큰을 기준으로 회원의 로그인 정보를 조회하고 푸시 토큰을 등록/수정한다)
     * </pre>
     */
    private void sendPutMemberAutoLogin() {

        try {
            HttpSend httpSend = new HttpSend(mActivity, false);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPutMemberAutoLogin(result);
                }
            });

            //공통 변수 입력
            httpSend.P_member(mAppConfig.getUuid(), mAppConfig.getPush_Token(),
                    Constants.OS_TYPE, mUtil.getHostName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <pre>
     * 멤버 자동 로그인 요청 결과.
     * (인증 토큰을 기준으로 회원의 로그인 정보를 조회하고 푸시 토큰을 등록/수정한다)
     * </pre>
     *
     * @param result 결과 data
     */
    private void resultPutMemberAutoLogin(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {

                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());

                //회원이미지 추가
                String imageFileName = "";
                if (joResult.has(Constants.KEY_IMAGE_FILE_NAME)) {
                    imageFileName = mUtil.null2string(joResult.get(Constants.KEY_IMAGE_FILE_NAME));
                    mAppConfig.setMy_Image_Url(imageFileName);
                }
                //회원명
                String nickname = "";
                if (joResult.has(Constants.KEY_NICKNAME)) {
                    nickname = mUtil.null2string(joResult.get(Constants.KEY_NICKNAME));
                    mAppConfig.setNickname(nickname);
                }

                String tempPasswordYn = "";
                if (joResult.has(Constants.KEY_TEMP_PASSWORD_YN)) {
                    tempPasswordYn = mUtil.null2string(joResult.get(
                            Constants.KEY_TEMP_PASSWORD_YN));
                }
                mAppConfig.setTemp_Password_Yn(tempPasswordYn);

                String invitationCount = "";
                if (joResult.has(Constants.KEY_INVITATIONS_COUNT)) {
                    invitationCount = mUtil.null2string(joResult.get(
                            Constants.KEY_INVITATIONS_COUNT));
                }

                String homegrpId = "";
                if (joResult.has(Constants.KEY_HOMEGRP_ID)) {
                    homegrpId = mUtil.null2string(joResult.get(Constants.KEY_HOMEGRP_ID));
                }

                String homegrpImageFileName = "";
                if (joResult.has(Constants.KEY_HOMEGRP_IMAGE_FILE_NAME)) {
                    homegrpImageFileName = mUtil.null2string(joResult.get(
                            Constants.KEY_HOMEGRP_IMAGE_FILE_NAME));
                }

                String homegrpName = "";
                if (joResult.has(Constants.KEY_HOMEGRP_NAME)) {
                    homegrpName = mUtil.null2string(joResult.get(Constants.KEY_HOMEGRP_NAME));
                }

                String gradeCode = "";
                if (joResult.has(Constants.KEY_GRADE_CODE)) {
                    gradeCode = mUtil.null2string(joResult.get(Constants.KEY_GRADE_CODE));
                }

                String homehubDeviceId = "";
                if (joResult.has(Constants.KEY_HOMEHUB_DEVICE_ID)) {
                    homehubDeviceId = mUtil.null2string(
                            joResult.get(Constants.KEY_HOMEHUB_DEVICE_ID));
                }

                String homehubConnState = "";
                if (joResult.has(Constants.KEY_DEVICE_CONN)) {
                    homehubConnState = mUtil.null2string(
                            joResult.get(Constants.KEY_DEVICE_CONN));
                }

                String homehubDongleState = "";
                if (joResult.has(Constants.KEY_DEVICE_ONLINE)) {
                    homehubDongleState = mUtil.null2string(
                            joResult.get(Constants.KEY_DEVICE_ONLINE));
                }

                String servicehubApplicationId = "";
                if (joResult.has(Constants.KEY_SERVICEHUB_APP_ID)) {
                    servicehubApplicationId = mUtil.null2string(joResult.get(
                            Constants.KEY_SERVICEHUB_APP_ID));
                }

                String deviceOnlineLastDatetime = "";
                if (joResult.has(Constants.KEY_DEVICE_ONLINE_LAST_DATETIME)) {
                    deviceOnlineLastDatetime = mUtil.null2string(joResult.get(
                            Constants.KEY_DEVICE_ONLINE_LAST_DATETIME));
                }

                //회원 번호
                String memberId = mUtil.null2string(joResult.get(Constants.KEY_MEMBER_ID));
                mAppConfig.setLogin_Member_Id(memberId);
                //이메일 ID
                String emailId = mUtil.null2string(joResult.get(Constants.KEY_EMAIL_ID));
                mAppConfig.setLogin_Id(emailId);
                mAppConfig.setLogin(true);

                //인증 토큰
                String authToken = mUtil.null2string(joResult.get(Constants.KEY_AUTH_TOKEN));
                //공통 변수 입력
                mAppConfig.setAuthToken(authToken);

                //db 입력작업
                SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
                String sql = "";
                sql = mSqlManager.qryDelLoginInfo();
                db.execSQL(sql);

                sql = "";
                Boolean isSaveId = false;
                sql = mSqlManager.qryInsertLoginInfo(emailId, authToken, isSaveId,
                        mAppConfig.getAutoLogin(), mAppConfig.getManualNotView(),
                        mAppConfig.getPush());
                db.execSQL(sql);
                db.close();

                String pushTypeModeChgYn = mUtil.null2string(joResult.get(
                        Constants.KEY_PUSH_TYPE_MODE_CHG_YN));
                mAppConfig.setPush_Type_Mode_Chg_Yn(pushTypeModeChgYn);
                String pushTypePrsncChgYn = mUtil.null2string(joResult.get(
                        Constants.KEY_PUSH_TYPE_PRSNC_CHG_YN));
                mAppConfig.setPush_Type_Prsnc_Chg_Yn(pushTypePrsncChgYn);
                mAppConfig.setInvitations_Count(invitationCount);
                mAppConfig.setCtrtGroupId(homegrpId);
                mAppConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
                mAppConfig.setSelect_Homegrp_Name(homegrpName);
                mAppConfig.setSelect_Homegrp_Grade_Code(gradeCode);
                mAppConfig.setSelect_Homegrp_Homehub_Device_Id(homehubDeviceId);
                mAppConfig.setsSelect_Homegrp_Homehub_Conn_State(homehubConnState);
                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State(homehubDongleState);
                mAppConfig.setsSelect_Servicehub_App_Id(servicehubApplicationId);
                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_Online_Last_Datetime(
                        deviceOnlineLastDatetime);

                processPush(invitationCount);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));

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

    /**
     * Push 타입에 따른 처리.
     *
     * @param invitationCount 초대 받은 횟수
     */
    private void processPush(String invitationCount) {
        if ("HOME_MEM_INV".equals(mPushTypeCode)) {
            //    홈 초대 받음
            if (mUtil.str2int(invitationCount) > 0) {
                Intent intent = new Intent(mActivity, InvitationList.class);
                mUtil.callActivityForResultNoAnim(mActivity, intent,
                        Constants.ACT_INVITATION_LIST);
                return;
            } else {
                displayView(Constants.MENU_THINGS);
            }
        } else if ("HOME_MEM_BAN".equals(mPushTypeCode)) {
            //    홈 강퇴 받음
            displayView(Constants.MENU_THINGS);
        } else if ("HOME_DEL".equals(mPushTypeCode)) {
            //    홈 삭제
            displayView(Constants.MENU_THINGS);
        } else if ("HOMEHUB_DEL".equals(mPushTypeCode)) {
            //    홈 허브가 삭제됨
            displayView(Constants.MENU_THINGS);
        } else if ("DVC_OWN_CHG".equals(mPushTypeCode)) {
            //    장치 소유주 변경 알림
            displayView(Constants.MENU_THINGS);
        } else if ("MEM_ALL_OUT".equals(mPushTypeCode)) {
            //    멤버 All out 시
            displayView(Constants.MENU_THINGS);
        } else if ("MEM_ANY_IN".equals(mPushTypeCode)) {
            //    멤버 Any in 시
            displayView(Constants.MENU_THINGS);
        } else if ("HOME_RELOAD".equals(mPushTypeCode)) {
            //    홈 멤버 정보 재조회 알림
            displayView(Constants.MENU_THINGS);
        }
        mPushTypeCode = "";
    }

    /**
     * 멤버 로그아웃 처리 요청.
     */
    private void sendGetMemberLogout() {

        try {
            HttpSend httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetMemberLogout(result);
                }
            });
            httpSend.G_member_logout();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 멤버 로그아웃 처리 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultGetMemberLogout(Response result) {

        mAppConfig.setAuthToken("");
        mAppConfig.setAutoLogin(false);
        SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
        String sql = "";
        sql = mSqlManager.qryUpdateLoginInfoAutoLogin(false);
        db.execSQL(sql);

        mAppConfig.setLogin_Pass("");

        if (mAppConfig.getAutoLogin()) {
            sql = "";
            sql = mSqlManager.qryUpdateLoginInfoLoginPass("");
            db.execSQL(sql);
        }

        mAppConfig.setLogin(false);
        mAppConfig.setMain(false);
        Dlog.v(mAppConfig.getIntro());
        mIntent = new Intent(mActivity, Login.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mUtil.callActivityNoAnim(mActivity, mIntent);
        finish();
    }

    /**
     * App 종료.
     */
    public void setExit() {

        Dlog.v("setExit()");
        mAppConfig.setIntro(false);
        mAppConfig.setGoErr(false);
        mAppConfig.setMain(false);
        finish();
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_MEMBER_LOGOUT:
                    sendGetMemberLogout();
                    break;
                case MSG_COM_G_MEMBER:
                    sendPutMemberAutoLogin();
                    break;
                case MSG_MAIN_INIT:
                    setInit();
                    break;
                case MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID:
                    sendDeleteHomegrpMember();
                    break;
                case MSG_COM_WS_DEVICE_ALIVE:
                    sendWsDeviceAlive();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
