/*
 * 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.db.DatabaseOpenHelper;
import com.ntels.onecable.common.db.SqlManager;
import com.ntels.onecable.common.handler.BackPressCloseHandler;
import com.ntels.onecable.common.handler.CallWithDelayHandler;
import com.ntels.onecable.common.util.Dlog;
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.CustomActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.invitation.InvitationList;

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.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import java.util.HashMap;


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

    private static final int MSG_COM_P_MEMBER_LOGIN = 1;
    private static final int MSG_COM_G_MEMBER = 2;
    private static final int VIBRATION_DURATION = 100;
    private static final int FINISH_INTERVAL = 1000;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private BackPressCloseHandler mBackPressCloseHandler;
    private int mType = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private SqlManager mSqlManager = new SqlManager();
    private Boolean mIsExit = false;    // 종료여부 묻기 플래그
    private Boolean mIsAutoLogin = false;
    private Boolean mIsSaveId = false;
    private String mId = "";
    private String mPass = "";
    private String mPushTypeCode = "";
    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;
    private OnWebSocketResponse webSocketResponse = new OnWebSocketResponse() {

        @Override
        public void onResponse(String result) {

            try {

                final JSONObject jsonObject = new JSONObject(result);
                final String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                Dlog.i("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));
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (messageType.equals(Constants.WEBSOCKET_TYPE_AUTH)) {
                            resultWsAuth(jsonObject);
                        } else if (messageType.equals(Constants.WEBSOCKET_TYPE_AUTH_AUTO)) {
                            resultWsAuth(jsonObject);
                        } else {

                    /*final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            util.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });*/
                        }
                    }
                });
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }

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

//            if (!mUtil.getTopActivityName(act).equals("view.Main")) {
//                return;
//            }
            switch (code) {
//                case Constants.WEBSOCKET_ERROR_TIMEOUT:
//                    Dlog.i("WEBSOCKET_ERROR_TIMEOUT!!!");
//                    for (HashMap<String, Object> hm : alTotalList) {
//                        hm.put(Constants.KEY_REQUEST_TIME, "");
//                    }
//                    break;
                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
                    Dlog.i("WEBSOCKET_ERROR_NOT_CONNECTED!!!");
                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
                    break;
                default:
                    break;
            }
        }
    };
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Dlog.i("onServiceConnected!!");
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            mWebSocketService = binder.getService();
            mWebSocketService.addWebSocketResponse(webSocketResponse);
            mIsBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mIsBound = false;
        }
    };
    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {

            String id = mUtil.getEditText(mActivity, R.id.edtId).getText().toString();
            String pass = mUtil.getEditText(mActivity, R.id.edtPass).getText().toString();

            if (mUtil.null2string(id).length() > 0 && mUtil.null2string(pass).length() > 0) {
                mUtil.getView(mActivity, R.id.btnLogin).setEnabled(true);
            } else {
                mUtil.getView(mActivity, R.id.btnLogin).setEnabled(false);
            }
        }
    };

    @Override
    protected void onNewIntent(Intent saveIntent) {

        super.onNewIntent(saveIntent);
        Dlog.v("jinointent");
        if (null != saveIntent) {
            mPushTypeCode = "";
            mPushTypeCode = mUtil.null2string(saveIntent.getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
            Dlog.v(mPushTypeCode);
            Boolean isTemp = saveIntent.getBooleanExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE, false);
            Dlog.v("isTemp", isTemp);
        }
    }

    @Override
    protected void onResume() {
        Dlog.i("onResume()!!");

        if (mWebSocketService != null) {
            Dlog.i("onResume1()!!");
            if (!mWebSocketService.isWebSocketConnected()) {
                Dlog.i("onResume2()!!");
                mWebSocketService.webSocketConnect();
                Dlog.i("onResume3()!!");
            }
        }
        super.onResume();
    }

    @Override
    protected void onPause() {

        super.onPause();

        if (mWebSocketService != null) {
            if (mWebSocketService.isWebSocketConnected()) {
                mWebSocketService.webSocketDisconnect();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

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

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

        Dlog.v("mAppConfig.getIntro()=" + mAppConfig.getIntro());
        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.login, null);
        this.setContentView(viewToLoad);

        if (savedInstanceState != null) {
            mIsExit = savedInstanceState.getBoolean(Constants.EXTRA_EXIT_FLAG, false);
        } else {
            mIntent = getIntent();
            mIsExit = mIntent.getBooleanExtra(Constants.EXTRA_EXIT_FLAG, false);
            mPushTypeCode = mUtil.null2string(getIntent().getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
        }

//        int height = mAppConfig.getDisplayHeight();
//        int tempHeight = (int) (height * 0.45);
//        LinearLayout.LayoutParams paramView3 = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, tempHeight);
//        mUtil.getView(mActivity, R.id.llbody1).setLayoutParams(paramView3);
//        mUtil.getView(mActivity, R.id.ivLogo).setLayoutParams(paramView3);

//        LinearLayout.LayoutParams paramView4 = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, height - tempHeight);
//        mUtil.getView(mActivity, R.id.llbody1).setLayoutParams(paramView4);
        mUtil.getView(mActivity, R.id.btnLogin).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnLogin).setEnabled(false);
        mUtil.getView(mActivity, R.id.tvJoin).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.tvIdFind).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.tvPassFind).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llAutoLogin).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llSaveId).setOnClickListener(this);

        mUtil.getViewUnderline(mActivity, R.id.tvJoin);
        mUtil.getViewUnderline(mActivity, R.id.tvIdFind);
        mUtil.getViewUnderline(mActivity, R.id.tvPassFind);

        mUtil.getEditText(mActivity, R.id.edtId).setText("");
        mUtil.getEditText(mActivity, R.id.edtPass).setText("");
//        mUtil.getEditText(mActivity, R.id.edtId).setText("welove75");
//        mUtil.getEditText(mActivity, R.id.edtPass).setText("78980250");
        mUtil.getEditText(mActivity, R.id.edtId).addTextChangedListener(mTextWatcher);
        mUtil.getEditText(mActivity, R.id.edtPass).addTextChangedListener(mTextWatcher);

        mUtil.setUserInfo(mActivity);
        mIsSaveId = mAppConfig.getSaveId();
        mIsAutoLogin = mAppConfig.getAutoLogin();
        Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
        Dlog.v("mIsSaveId =" + mIsSaveId);
        mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(mIsAutoLogin);
        mUtil.getView(mActivity, R.id.llSaveId).setSelected(mIsSaveId);
        if (mIsAutoLogin) {
            mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.INVISIBLE);
            mId = mAppConfig.getLogin_Id();
            mPass = "";
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
        } else {
            mUtil.getView(mActivity, R.id.llAutoLogin).performClick();
        }
        if (mIsSaveId) {
            mId = mAppConfig.getLogin_Id();
            if (!"".equals(mId)) {
                mUtil.getEditText(mActivity, R.id.edtId).setText(mId);
                mUtil.getEditText(mActivity, R.id.edtId).setSelection(mId.length());
            }
        }
        mUtil.setKeyboardHide(mActivity, mUtil.getLinearLayout(mActivity, R.id.llSvbody));

    }

    /**
     * 서비스허브에 노드 동기화를 요청한다.(데이터 동기화 아님)
     */
    private void sendWssTest() {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_AUTH);
        sendParams.put(Constants.KEY_MEMBER_ID, "100");
        sendParams.put(Constants.KEY_MEMBER_PASSWORD, "1234");
        sendParams.put(Constants.KEY_OS_TYPE, Constants.OS_TYPE);
        sendParams.put(Constants.KEY_CUST_ID, "1002");
        sendParams.put(Constants.KEY_CTRT_GRP_ID, "1002");
        mWebSocketService.send(Constants.WEBSOCKET_SEND_AUTH, sendParams);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mIsExit = savedInstanceState.getBoolean(Constants.EXTRA_EXIT_FLAG, false);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        outState.putBoolean(Constants.EXTRA_EXIT_FLAG, mIsExit);
    }

    @Override
    public void onBackPressed() {

        mBackPressCloseHandler.onBackPressed("setExit");
    }

    @Override
    public void setAnimFinish(String val) {

        super.setAnimFinish(val);
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        Boolean isReload = false;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_ERROR_PAGE:
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType),
                            Constants.HANDLER_DELAY_MILLIS);
                    break;
                case Constants.ACT_JOIN:
                    //setFinish();
                    break;
                case Constants.ACT_LOGIN_NEW_DEVICE:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
                    } else {
                        setFinish();
                    }
                    break;
                case Constants.ACT_LOGIN_DEVICE_OVER:
                    mIntent = new Intent(mActivity, LoginNewDevice.class);
                    String emailId = mUtil.null2string(data.getStringExtra(Constants.EXTRA_EMAIL_ID));
                    mIntent.putExtra(Constants.EXTRA_EMAIL_ID, emailId);
                    String nickname = mUtil.null2string(data.getStringExtra(Constants.EXTRA_NICKNAME));
                    mIntent.putExtra(Constants.EXTRA_NICKNAME, nickname);
                    String deviceSn = mUtil.null2string(data.getStringExtra(Constants.KEY_DEVICE_SN));
                    mIntent.putExtra(Constants.KEY_DEVICE_SN, deviceSn);
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_LOGIN_NEW_DEVICE);
                    break;
                case Constants.ACT_INVITATION_LIST:
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_MEMBER),
                            Constants.HANDLER_DELAY_MILLIS);
                    break;
                default:
                    break;
            }
        } else {
            if (mAppConfig.getGoErr()) {
                setExit();
            } else {
                switch (requestCode) {
                    case Constants.ACT_INVITATION_LIST:
                        setFinish();
                        break;
                    default:
                        break;
                }
            }
        }
    }

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

        switch (msgId) {
            case Constants.MSG801:
                if (btnResult == 1) {
                    Dlog.v("jino test");
                }
                break;
            case Constants.MSG804:
                if (btnResult == 1) {
                    setExit();
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    setExit();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llAutoLogin:
                if (mIsAutoLogin) {
                    mIsAutoLogin = false;
                } else {
                    mIsAutoLogin = true;
                }
                mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(mIsAutoLogin);
                break;
            case R.id.llSaveId:
                if (mIsSaveId) {
                    mIsSaveId = false;
                } else {
                    mIsSaveId = true;
                }
                mUtil.getView(mActivity, R.id.llSaveId).setSelected(mIsSaveId);
                break;
            case R.id.btnLogin:
                mPass = "";
                mPass += mUtil.getEditTextVal(mActivity, R.id.edtPass).trim();
                mId = "";
                mId += mUtil.getEditTextVal(mActivity, R.id.edtId).trim();

                if (!checkFormValid()) {
                    mUtil.setShowToast(mActivity,
                            mUtil.getString(mActivity, R.string.MSG802), Toast.LENGTH_SHORT);
                    return;
                }
                mUtil.setVibrator(VIBRATION_DURATION);
                view.setEnabled(false);
                comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_MEMBER_LOGIN), Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.tvJoin:
                mIntent = new Intent(mActivity, JoinCheck.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_JOIN_CHK);
                break;
            // TODO: 2017-03-27 ID찾기 화면 연결하기
            case R.id.tvIdFind:
                mIntent = new Intent(mActivity, ResetPassword.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_RESET_PASSWORD);
                break;
            case R.id.tvPassFind:
                mIntent = new Intent(mActivity, ResetPassword.class);
                mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_RESET_PASSWORD);
                break;
            default:
                break;
        }
    }

    /**
     * 사용자 입력 필드 체크.
     *
     * @return 체크 결과
     */
    private Boolean checkFormValid() {

        Boolean isCheck = true;

        if (mId.trim().length() < 1) {
            isCheck = false;
        }
        if (mPass.trim().length() < 1) {
            isCheck = false;
        }
        return isCheck;
    }

    /**
     * 멤버 로그인 요청.
     */
    private void sendWsMemberAuth() {

        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_AUTH);
        sendParams.put(Constants.KEY_MEMBER_ID, mId);
        sendParams.put(Constants.KEY_PASSWORD, mPass);
        sendParams.put(Constants.KEY_OS_TYPE, Constants.OS_TYPE);
        sendParams.put(Constants.KEY_DEVICE_TOKEN, mAppConfig.getPush_Token());
        Dlog.v(sendParams);
        mWebSocketService.send(Constants.WEBSOCKET_SEND_AUTH, sendParams);
    }

    /**
     * 자동로그인  로그인 요청.
     */
    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());
        Dlog.v(sendParams);
        mWebSocketService.send(Constants.WEBSOCKET_SEND_AUTH_AUTO, sendParams);
    }


//    /**
//     * 멤버 로그인 요청.
//     */
//    private void sendPostMemberLogin() {
//
//        try {
//            HttpSend httpSend = new HttpSend(mActivity);
//            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
//                @Override
//                public void resultResponse(Response result) {
//
//                    resultWsAuth(result);
//                }
//            });
//            httpSend.P_member_login(mId, mPass, mAppConfig.getService_Id(), Constants.OS_TYPE, mAppConfig.getUuid(), mAppConfig
//                    .getPush_Token(), mUtil.getPhoneName(), mUtil.getHostName());
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }

//    /**
//     * <pre>
//     * 멤버 자동 로그인 요청.
//     * (인증 토큰을 기준으로 회원의 로그인 정보를 조회하고 푸시 토큰을 등록/수정한다)
//     * </pre>
//     */
//    private void sendPutMemberAutoLogin() {
//
//        try {
//            HttpSend httpSend = new HttpSend(mActivity);
//            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
//                @Override
//                public void resultResponse(Response result) {
//
//                    resultWsAuth(result);
//                }
//            });
//
//            //공통 변수 입력
//            httpSend.P_member(mAppConfig.getUuid(), mAppConfig.getPush_Token(), Constants.OS_TYPE, mUtil.getHostName());
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }

    /**
     * 멤버 로그인 요청 결과.
     *
     * @param jsonObject 결과 data
     */
    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)) {

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

                //계약 그룹 ID
                String ctrtGroupId;
                if (joResult.has(Constants.KEY_CUST_ID)) {
                    ctrtGroupId = mUtil.null2string(joResult.get(Constants.KEY_CTRT_GRP_ID));
                    mAppConfig.setCtrtGroupId(ctrtGroupId);
                }

                //회원이미지 추가
                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 invitationsCount = "";
                if (joResult.has(Constants.KEY_INVITATIONS_COUNT)) {
                    invitationsCount = mUtil.null2string(joResult.get(Constants.KEY_INVITATIONS_COUNT));
                }

                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));
                }

                // TODO: 2017-03-21 테스트 후 joResult2 관련 소스 모두 삭제.
                JSONObject joResult2 = joResult.getJSONArray(Constants.KEY_DEVICE_LIST).getJSONObject(0);

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

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

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

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

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

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

                //회원 번호
                String memberId = mId;
                mAppConfig.setLogin_Member_Id(memberId);
                //이메일 ID
//                String emailId = mUtil.null2string(joResult.get(Constants.KEY_EMAIL_ID));
                mAppConfig.setLogin_Id(mId);
                if ("Y".equals(tempPasswordYn)) {
                    mAppConfig.setLogin_Pass(mPass);
                } else {
                    mAppConfig.setLogin_Pass("");
                }
                mAppConfig.setAutoLogin(mIsAutoLogin);
                mAppConfig.setSaveId(mIsSaveId);
                mAppConfig.setLogin(true);

                //인증 토큰
                String authToken = "";
                if (joResult2.has(Constants.KEY_AUTH_TOKEN)) {
                    authToken = mUtil.null2string(joResult.get(Constants.KEY_AUTH_TOKEN));
                    //공통 변수 입력
                    mAppConfig.setAuthToken(authToken);
                } else {
                    authToken = mAppConfig.getAuthToken();
                }


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

                sql = "";
                Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
                sql = mSqlManager.qryInsertLoginInfo(memberId, authToken, mIsSaveId, mIsAutoLogin, 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(invitationsCount);
                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_Device_Key(homehubDeviceKey);
                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);
                if (!"".equals(homehubDeviceId)) {
                    mAppConfig.setIsHomegrpHomehub(true);
                }

                if (mUtil.str2int(invitationsCount) > 0) {
                    Intent intent = new Intent(mActivity, InvitationList.class);
                    mUtil.callActivityForResultNoAnim(mActivity, intent,
                            Constants.ACT_INVITATION_LIST);
                    return;
                }

                setFinish();
                return;
            } 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)) {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, 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 {
                    mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mUtil.getView(mActivity, R.id.llRoot).setVisibility(View.VISIBLE);
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }

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

    /**
     * 종료 후 메인으로 이동.
     */
    private void setFinish() {

        Intent intent = new Intent(mActivity, Main.class);
        intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, "");
        mUtil.callActivityNoAnim(mActivity, intent);

        setFinishLoading();
    }

    /**
     * 로딩 완료.
     */
    public void setFinishLoading() {
        new CallWithDelayHandler(this).callFinishWithDelay("isFinish");
    }

    private Boolean isFinish() {
        if (!mAppConfig.getMain()) {
            return false;
        } else {
            return true;
        }
    }

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

        Dlog.v("setExit()");
        mAppConfig.setIntro(false);
        mAppConfig.setGoErr(false);
        mAppConfig.setMain(false);
        setResult(RESULT_CANCELED, new Intent());
        finish();
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_MEMBER_LOGIN:
//                    sendWsMemberAuth();
                    new CallWithDelayHandler(mActivity).callWithDelay("getWebSocketState", "sendWsMemberAuth");
                    break;
                case MSG_COM_G_MEMBER:
                    // 추후 바
//                    sendWsMemberAuth();
                    new CallWithDelayHandler(mActivity).callWithDelay("getWebSocketState", "sendWsMemberAuthAuto");
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private Boolean getWebSocketState(){
        Boolean isWebSocketState = false;
        if (mWebSocketService.isWebSocketConnected()) {
            isWebSocketState = true;
        }
        return  isWebSocketState;
    }
}
