/*
 * 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.WebSocketService;
import com.ntels.onecable.common.widget.CustomActivity;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
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;

import static com.ntels.onecable.common.Constants.EXTRA_ERROR_CODE;
import static com.ntels.onecable.common.Constants.EXTRA_RESULT_STATE;
import static com.ntels.onecable.common.Constants.KEY_CTRT_GRP_NAME;
import static com.ntels.onecable.common.broadcast.DefaultLocalBroadCast.INTENT_NAME_TYPE;

/**
 * <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 CustomActivity 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;
    private Handler mComHandler = 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;

    @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)) {
                //    홈 초대 받음
                mComHandler.sendMessageDelayed(mComHandler.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!!");
                //    홈 강퇴 받음
//                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
                onLogout();
            } else if ("HOME_MEM_SEL".equals(mPushTypeCode)) {
                //    홈 자진 탈퇴 받음
            } else if ("HOME_DEL".equals(mPushTypeCode)) {
                //    홈 삭제
                mComHandler.sendMessageDelayed(mComHandler.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)) {
                //    홈 허브가 삭제됨
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("DVC_OWN_CHG".equals(mPushTypeCode)) {
                //    장치 소유주 변경 알림
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("MEM_ALL_OUT".equals(mPushTypeCode)) {
                //    멤버 All out 시
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("MEM_ANY_IN".equals(mPushTypeCode)) {
                //    멤버 Any in 시
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("HOME_RELOAD".equals(mPushTypeCode)) {
                //    홈 멤버 정보 재조회 알림
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("LOGOUT".equals(mPushTypeCode)) {
                //    강제 로그아웃 시킴
                onLogout();
            } else if ("MAS_GRD".equals(mPushTypeCode)) {
                // 마스터 권한 양도
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("MAS_GRD_ACCEPT".equals(mPushTypeCode)) {
                // 마스터 권한 양도 수락
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("MAS_GRD_REJECT".equals(mPushTypeCode)) {
                // 마스터 권한 양도 거절
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
            } else if ("MOBILE_NUM_CHG".equals(mPushTypeCode)) {
                // 휴대폰 번호 인증 필요
            } else if ("HOMEHUB_OFF".equals(mPushTypeCode)) {
                // 홈허브 오프라인
            }

            if (!"".equals(mPushTypeCode)) {
                processPush("");
            }

            if (saveIntent.hasExtra(Constants.EXTRA_BUNDLE_DATA)) {
                Bundle receivedData = saveIntent.getBundleExtra(Constants.EXTRA_BUNDLE_DATA);
                Intent intentReceived = new Intent();

                intentReceived.putExtras(receivedData);
                String nameType = intentReceived.getStringExtra(INTENT_NAME_TYPE);

                if (nameType.equals(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE)) {
                    if (mFragmentPosition == Constants.MENU_THINGS) {
                        FragmentThings fragment = (FragmentThings) getSupportFragmentManager().findFragmentById(R.id.frame_container);
                        fragment.setHomeHubStateAll();
                    } else if (mFragmentPosition == Constants.MENU_HOMEMEMBER) {
                        FragmentHomeMember fragment = (FragmentHomeMember) getSupportFragmentManager().findFragmentById(R.id
                                .frame_container);
                        fragment.setHomeHubStateAll();
                    } else if (mFragmentPosition == Constants.MENU_RULES) {
                        FragmentRules fragment = (FragmentRules) getSupportFragmentManager().findFragmentById(R.id.frame_container);
                        fragment.setHomeHubStateAll();
                    }
                } else if (nameType.equals(KneetMessageLocalBroadCast.INTENT_ACTION_WEBSOCKET_MSG_RECEIVED)) {
                    if (mFragmentPosition == Constants.MENU_THINGS) {
                        FragmentThings fragment = (FragmentThings) getSupportFragmentManager().findFragmentById(R.id.frame_container);
                        fragment.recevicedWebSocket(intentReceived);
                    }
//                    if (mFragmentPosition == Constants.MENU_HOMEMEMBER) {
//                        FragmentHomeMember fragment = (FragmentHomeMember) getSupportFragmentManager().findFragmentById(R.id
// .frame_container);
//                        fragment.recevicedWebSocket(intentReceived);;
//                    }
//                    if (mFragmentPosition == Constants.MENU_RULES) {
//                        FragmentRules fragment = (FragmentRules) getSupportFragmentManager().findFragmentById(R.id.frame_container);
//                        fragment.recevicedWebSocket(intentReceived);
//                    }

                }
            }
        }
    }

    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                LogUtil.i(TAG, "websocket message mType : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if (jsonObject.has(Constants.KEY_RESULT_CODE)) {
                    resultCode = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_CODE));
                }
                if (jsonObject.has(Constants.KEY_RESULT_MSG)) {
                    resultMsg = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_MSG));
                }
                if (messageType.equals(Constants.WEBSOCKET_TYPE_DEVICE_CONTENT)) {
                    notificationWsDeviceContent(jsonObject);
                } else if (Constants.WEBSOCKET_TYPE_AUTH.equals(messageType)) {
                    if (mAppConfig.getIsWebSocketAuth()) {
                        mComHandler.sendEmptyMessageDelayed(MSG_COM_WS_DEVICE_ALIVE, Constants.HANDLER_DELAY_MILLIS);
                    }
                } else if (Constants.WEBSOCKET_TYPE_DEVICE_ALIVE.equals(messageType)) {
                    resultWsDeviceAlive(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_AUTH_AUTO)) {
                    resultWsAuth(jsonObject);
                } else {
//                    return;


                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {
            Dlog.v("WebSocketService.WEBSOCKET_RECEIVED_ERROR");
            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
            switch (errorCode) {

            }

        }
    }

    ;

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

        setIsWebSocket(true);
        setIsMain(true);

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

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

        mAppConfig.setMain(true);
    }

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

        super.onResume();
    }

    @Override
    protected void onPause() {

        super.onPause();

    }

    /**
     * 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);
        mUtil.getView(mActivity, R.id.llMainNavi4).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()");

    }

    @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:
                        mComHandler.sendMessageDelayed(mComHandler.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 (getWebSocketService() != null && !getWebSocketService().isWebSocketConnected()) {
//                            getWebSocketService().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");
//        mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_G_MEMBER_LOGOUT));
        mAppConfig.setAuthToken("");
        mAppConfig.setIsAutoLogin(false);
        SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
        String sql = "";
        sql = mSqlManager.qryUpdateLoginInfoAutoLogin(false);
        db.execSQL(sql);

        mAppConfig.setLogin_Pass("");

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

        mAppConfig.setIsLogin(false);
        mAppConfig.setMain(false);
        mAppConfig.setUpdateShow(true);
        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();
    }

    @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) {
//                    mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_G_MEMBER_LOGOUT));
                    onLogout();
                }
                break;
            case Constants.MSG835:
                if (btnResult == 1) {
                    mComHandler.sendMessage(mComHandler.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 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 ("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.MSG000, resultMsg);
                }
            }
        } 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.getSelectHomehubDeviceId());
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());

        getWebSocketService().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.getSelectHomehubDeviceId())) {
            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.getSelectCtrtGroupHomehubOnlineState(deviceId);

            mAppConfig.getDevicesList(deviceId).put(Constants.KEY_DEVICE_CONN, deviceConn);
            mAppConfig.getDevicesList(deviceId).put(Constants.KEY_DEVICE_ONLINE, deviceOnline);

            String currentOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);

            if (!currentOnlineStatus.equals(preOnlineStatus)) {
                //상태가 변경되었을때만 브로드캐스트를 날려준다
                Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                intent.putExtra(INTENT_NAME_TYPE, KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE);
                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 deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
            String preOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);
            String pushOnlineStatus = mUtil.null2string(((JSONObject) joResult.get(Constants.KEY_CONTENT_VALUE)).getString(Constants
                    .KEY_ONLINE));
            String currentOnlineStatus = "";

            mAppConfig.getDevicesList(deviceId).put(Constants.KEY_DEVICE_ONLINE, pushOnlineStatus);
            mAppConfig.getDevicesList(deviceId).put(Constants.KEY_DEVICE_CONN, "connect");

            currentOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);

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

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

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_AUTH_AUTO);
        sendParams.put(Constants.KEY_AUTHORIZATION, mAppConfig.getAuthorization());
        sendParams.put(Constants.KEY_OS_TYPE, Constants.OS_TYPE);
        sendParams.put(Constants.KEY_DEVICE_TOKEN, mAppConfig.getPush_Token());
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());
        Dlog.v(sendParams);
        getWebSocketService().send(Constants.WEBSOCKET_SEND_AUTH_AUTO, sendParams);
    }

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

        Dlog.i("resultWsAuth!!");

        try {
            JSONObject joResult = jsonObject;
            Dlog.v(joResult.toString());

            String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));

            if ("00".equals(resultCode)) {

                //request ID
                String requestId = "";
                if (joResult.has(Constants.KEY_REQUEST_ID)) {
                    requestId = mUtil.null2string(joResult.get(Constants.KEY_REQUEST_ID));
                }

                //회원 ID
                String memberId = "";
                if (joResult.has(Constants.KEY_MEMBER_ID)) {
                    memberId = mUtil.null2string(joResult.get(Constants.KEY_MEMBER_ID));
                }

                //인증 토큰
                String authToken = "";
                if (joResult.has(Constants.KEY_AUTH_TOKEN)) {
                    authToken = mUtil.null2string(joResult.get(Constants.KEY_AUTH_TOKEN));
                } else {
                    authToken = mAppConfig.getAuthToken();
                }

                //회원이미지 추가
                String profileImage = "";
                if (joResult.has(Constants.KEY_PROFILE_IMAGE)) {
                    profileImage = mUtil.null2string(joResult.get(Constants.KEY_PROFILE_IMAGE));
                }

                //회원명
                String nickname = "";
                if (joResult.has(Constants.KEY_NICKNAME)) {
                    nickname = mUtil.null2string(joResult.get(Constants.KEY_NICKNAME));
                }

                //고객 ID
                String custId = "";
                if (joResult.has(Constants.KEY_CUST_ID)) {
                    custId = mUtil.null2string(joResult.get(Constants.KEY_CUST_ID));
                }

                //퀴즈
                String quiz = "";
                if (joResult.has(Constants.KEY_QUIZ)) {
                    quiz = mUtil.null2string(joResult.get(Constants.KEY_QUIZ));
                }

                //phone
                String phone = "";
                if (joResult.has(Constants.KEY_PHONE)) {
                    phone = mUtil.null2string(joResult.get(Constants.KEY_PHONE));
                }

                //phone_auth_yn
                String phoneAuthYn = "";
                if (joResult.has(Constants.KEY_PHONE_AUTH_YN)) {
                    phoneAuthYn = mUtil.null2string(joResult.get(Constants.KEY_PHONE_AUTH_YN));
                }

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

                //마지막 선택된 계약그룹 ID
                String selectCtrtGrpId = mUtil.null2string(joResult.get(Constants.KEY_SELECT_CTRT_GRP_ID));

                JSONArray jaCtrtGrpList = joResult.getJSONArray(Constants.KEY_CTRT_GRP_LIST);
                for (int i = 0; i < jaCtrtGrpList.length(); i++) {
                    JSONObject joCtrtGrpList = jaCtrtGrpList.getJSONObject(i);

                    //계약그룹 ID
                    String ctrtGrpId = mUtil.null2string(joCtrtGrpList.get(Constants.KEY_CTRT_GRP_ID));

                    if ("".equals(selectCtrtGrpId) || selectCtrtGrpId.equals(ctrtGrpId)) {
                        //ctrt_grp_name
                        String ctrtGrpName = "";
                        if (joCtrtGrpList.has(KEY_CTRT_GRP_NAME)) {
                            ctrtGrpName = mUtil.null2string(joCtrtGrpList.get(KEY_CTRT_GRP_NAME));
                        }

                        //firmware_update_yn
                        String firmwareUpdateYn = "";
                        if (joCtrtGrpList.has(Constants.KEY_FIRMWARE_UPDATE_YN)) {
                            firmwareUpdateYn = mUtil.null2string(joCtrtGrpList.get(Constants.KEY_FIRMWARE_UPDATE_YN));
                        }

                        //push_type_mode_chg_yn
                        String pushTypeModeChgYn = "";
                        if (joCtrtGrpList.has(Constants.KEY_PUSH_TYPE_MODE_CHG_YN)) {
                            pushTypeModeChgYn = mUtil.null2string(joCtrtGrpList.get(Constants.KEY_PUSH_TYPE_MODE_CHG_YN));
                        }


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

                        //push_type_mode_chg_yn
                        String masterTransferPopupYn = "";
                        if (joCtrtGrpList.has(Constants.KEY_MASTER_TRANSFER_POPUP_YN)) {
                            masterTransferPopupYn = mUtil.null2string(joCtrtGrpList.get(Constants.KEY_MASTER_TRANSFER_POPUP_YN));
                        }

                        Boolean deviceExistYn = false;
                        if (joCtrtGrpList.has(Constants.KEY_DEVICE_EXIST_YN)) {
                            deviceExistYn = mUtil.null2string(joCtrtGrpList.get(Constants.KEY_DEVICE_EXIST_YN)).equals("Y") ? true : false;
                        }
                        // master_name
                        String masterName = "";
                        if (joCtrtGrpList.has(Constants.KEY_MASTER_NAME)) {
                            masterName = mUtil.null2string(joCtrtGrpList.get(Constants.KEY_MASTER_NAME));
                        }

                        mAppConfig.setCtrtGroupId(ctrtGrpId);
                        mAppConfig.setCtrtGroupName(ctrtGrpName);
                        mAppConfig.setCtrtGroupGradeCode(gradeCode);
                        mAppConfig.setIsCtrtGroupHomehub(deviceExistYn);
                        mAppConfig.setPush_Type_Mode_Chg_Yn(pushTypeModeChgYn);
                        mAppConfig.setMasterTransferPopupYn(masterTransferPopupYn);
                        mAppConfig.setCtrtMasterName(masterName);
//                mAppConfig.setSelect_Homegrp_Icon(homegrpImageFileName);

                    }
                }
//                mAppConfig.setIsLogin(true);
//                mAppConfig.setIsAutoLogin(mIsAutoLogin);
//                mAppConfig.setSaveId(mIsSaveId);
//                mAppConfig.setLoginId(mId);
//                mAppConfig.setLoginMemberId(memberId);
                mAppConfig.setMyImageUrl(profileImage);
                mAppConfig.setAuthToken(authToken);
                mAppConfig.setNickname(nickname);
                mAppConfig.setCustId(custId);
                mAppConfig.setQuiz(quiz);
                mAppConfig.setPhone(phone);
                mAppConfig.setTemp_Password_Yn(tempPasswordYn);
                mAppConfig.setPhoneAuthYn(phoneAuthYn);

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

                sql = "";
                Dlog.v("mIsAutoLogin =" + mAppConfig.getIsAutoLogin());
                sql = mSqlManager.qryInsertLoginInfo(
                        mAppConfig.getLoginMemberId()
                        , authToken
                        , mAppConfig.getSaveId()
                        , mAppConfig.getIsAutoLogin()
                        , mAppConfig.getManualNotView()
                        , mAppConfig.getPush());
                db.execSQL(sql);
                db.close();
            } else {
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                if ("71".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG924);
                } else if ("401".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
//                } else if ("401-101".equals(resultCode)) {
//                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG828, mId, R.string.MSG_TITLE_001);
//                } else if ("401-103".equals(resultCode)) {
//                    String nickname = mUtil.null2string(joResult.get(Constants.KEY_NICKNAME));
//                    Intent intent = new Intent(mActivity, LoginNewDevice.class);
//                    intent.putExtra(Constants.EXTRA_EMAIL_ID, mId);
//                    intent.putExtra(Constants.EXTRA_NICKNAME, nickname);
//                    mUtil.callActivityForResult(mActivity, intent, Constants.ACT_LOGIN_NEW_DEVICE);
                } else if ("401-106".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } 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);
        } else if ("MAS_GRD_ACCEPT".equals(mPushTypeCode)) {
            //    현재 화면 갱신
            displayView(mFragmentPosition);
        } else if ("MAS_GRD".equals(mPushTypeCode)) {
            //    현재 화면 갱신
            displayView(mFragmentPosition);
        } else if ("MAS_GRD_REJECT".equals(mPushTypeCode)) {
            //    현재 화면 갱신
            displayView(mFragmentPosition);
        }
        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.setIsAutoLogin(false);
        SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
        String sql = "";
        sql = mSqlManager.qryUpdateLoginInfoAutoLogin(false);
        db.execSQL(sql);

        mAppConfig.setLogin_Pass("");

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

        mAppConfig.setIsLogin(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);
        getWebSocketService().webSocketDisconnect();
        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:
                    sendWsMemberAuthAuto();
                    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;
        }
    }
}
