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

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

import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.AppConfig;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.db.DatabaseOpenHelper;
import com.ntels.onecable.admin.common.db.SqlManager;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.common.widget.CustomActivity;
import com.ntels.onecable.admin.view.HomeStart;
import com.ntels.onecable.admin.view.ImageSelect;
import com.ntels.onecable.admin.view.dialog.CustomDialog;

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.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.ntels.onecable.admin.common.Constants.EXTRA_ERROR_CODE;
import static com.ntels.onecable.admin.common.Constants.EXTRA_RESULT_STATE;
import static com.ntels.onecable.admin.common.Constants.KEY_CTRT_GRP_NAME;

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

    private static final int MSG_COM_P_MEMBER_PROFILE_IMAGE = 1;
    private static final int MSG_COM_WS_AUTH_AUTO = 2;
    private static final int MSG_COM_P_MEMBER_PUSH_NOTI = 3;
    private static final int MSG_COM_D_MEMBER = 4;

    private static final int ALRAM_MODE_ON = 1;
    private static final int ALRAM_MODE_OFF = 2;
    private static final int ALRAM_RULE_ON = 3;
    private static final int ALRAM_RULE_OFF = 4;
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    /*통신 관련*/
    private int type = 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 mIsAutoLogin = false;
    private Boolean mIsSaveId = false;
    private String mLoginId = "";
    private String mFileName = "";
    private String pushTypeModeChgYn = "";
    private String pushTypeRuleExcYn = "";
    private String newEmailId = "";
    private int alarmType = 0;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean loading = false;
    @BindView(R.id.tvQuiz) TextView mQuiz;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

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

        setIsWebSocket(true);

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

        setToolbar();
        displayListView();
    }

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

        Toolbar toolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, toolbar);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1)
                .setText(mUtil.getString(mActivity, R.string.layout_setting_01));
    }

    private void displayListView() {

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

                if (!loading) {
                    loading = true;
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_WS_AUTH_AUTO), Constants.HANDLER_DELAY_MILLIS);
                }
            }
        });
        setDisp();
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_WS_AUTH_AUTO), Constants.HANDLER_DELAY_MILLIS);
    }

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

        mUtil.getView(mActivity, R.id.rlMemberImage).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llAutoLogin).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnLogout).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llGotoService).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llGotoPolicy).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llAlramHomeMode).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnWithdrawal).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnChangeNickname).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnChangeCellphone).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnChangePassword).setOnClickListener(this);

        String url = mAppConfig.getMyImageUrl();
        mUtil.setRefreshImage(mActivity, url, mUtil.getImageView(mActivity, R.id.ivMemberIcon));

        if ("".equals(mAppConfig.getNickname())) {
            mUtil.getTextView(mActivity, R.id.tvNickname).setText(getString(R.string.layout_setting_nickname_change_05));
        } else {
            mUtil.getTextView(mActivity, R.id.tvNickname).setText(mAppConfig.getNickname());
        }
        mUtil.getTextView(mActivity, R.id.tvCellphone).setText(mUtil.insertHyphenPhone(mAppConfig.getPhone()));
        mUtil.getTextView(mActivity, R.id.tvAppVersion).setText(mUtil.getVersionName(mActivity));
        mQuiz.setText(mAppConfig.getQuiz());

        mIsAutoLogin = mAppConfig.getIsAutoLogin();
        mIsSaveId = mAppConfig.getSaveId();
        mLoginId = mAppConfig.getLoginId();

        Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
        if (mIsAutoLogin) {
            mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(true);
        } else {
            mUtil.getView(mActivity, R.id.llAutoLogin).setSelected(false);
        }

        pushTypeModeChgYn = mAppConfig.getPush_Type_Mode_Chg_Yn();
        if (mAppConfig.getPush_Type_Mode_Chg_Yn().equals("Y")) {
            mUtil.getView(mActivity, R.id.llAlramHomeMode).setSelected(true);
        } else {
            mUtil.getView(mActivity, R.id.llAlramHomeMode).setSelected(false);
        }

        if (mAppConfig.getSelectCtrtGroupHomehubOnlineState().equals("ON")) {
            mUtil.getView(mActivity, R.id.llAlramHomeMode).setEnabled(true);
        } else {
            mUtil.getView(mActivity, R.id.llAlramHomeMode).setEnabled(false);
        }
        if (Constants.GRADE_CODE_SIM.equals(mAppConfig.getCtrtGroupGradeCode())) {
            mUtil.getView(mActivity, R.id.btnWithdrawal).setVisibility(View.VISIBLE);
        } else {
            mUtil.getView(mActivity, R.id.btnWithdrawal).setVisibility(View.GONE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                break;
            case R.id.rlMemberImage:
                mIntent = new Intent(mActivity, ImageSelect.class);
                mIntent.putExtra(Constants.EXTRA_CROP_TYPE, true);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_IMAGE_SELECT);
                break;
            case R.id.llAutoLogin:
                if (view.isSelected()) {
                    view.setSelected(false);
                } else {
                    view.setSelected(true);
                }
                mIsAutoLogin = view.isSelected();
                mAppConfig.setIsAutoLogin(mIsAutoLogin);
                //db 입력작업
                SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
                String sql = "";
                sql = "";
                sql = mSqlManager.qryUpdateLoginInfoAutoLogin(mIsAutoLogin);
                db.execSQL(sql);
                db.close();
                break;
            case R.id.btnLogout:
                mCustomDialog.msgAlert(mActivity, Constants.MSG805);
                break;
            case R.id.llAlramHomeMode:
                view.setEnabled(false);
                if (view.isSelected()) {
                    pushTypeModeChgYn = "N";
                    alarmType = ALRAM_MODE_OFF;
                } else {
                    pushTypeModeChgYn = "Y";
                    alarmType = ALRAM_MODE_ON;
                }
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_MEMBER_PUSH_NOTI), Constants.HANDLER_DELAY_MILLIS);
                break;
            case R.id.llGotoService:
                mIntent = new Intent(Intent.ACTION_VIEW);
                mIntent.addCategory(Intent.CATEGORY_DEFAULT);
                mIntent.setData(Uri.parse(Constants.URL_TERMS_OF_SERVICE));
                startActivity(mIntent);
                break;
            case R.id.llGotoPolicy:
                mIntent = new Intent(Intent.ACTION_VIEW);
                mIntent.addCategory(Intent.CATEGORY_DEFAULT);
                mIntent.setData(Uri.parse(Constants.URL_TERMS_OF_POLICY));
                startActivity(mIntent);
                break;
            case R.id.btnWithdrawal:
                mCustomDialog.msgAlert(mActivity, Constants.MSG937, R.string.MSG_TITLE_009);
                // 홈그룹의 마스터이며 홈허브가 등록되어있으면 홈허브를 먼저 삭제하라는 메세지 노출.
                // 회원탈퇴 시 MAS에서 홈허브 삭제가 자동으로 이루어지지 않음.
                /*if (mAppConfig.getCtrtGroupGradeCode().equalsIgnoreCase("MAS")
                        && !mAppConfig.getSelectHomehubDeviceId().equals("")) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG909), Toast.LENGTH_SHORT);
                } else {
                    if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG910);
                    } else {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG911);
                    }
                }*/
                break;
            case R.id.btnChangeNickname:
                mIntent = new Intent(mActivity, SettingNicknameChange.class);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_SETTING_NICKNAME_CHANGE);
                break;
            case R.id.btnChangeCellphone:
                mIntent = new Intent(mActivity, SettingCellphoneChange.class);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_SETTING_CELLPHONE_CHANGE);
                break;
            case R.id.btnChangePassword:
                mIntent = new Intent(mActivity, SettingPasswordCheck.class);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_SETTING_PASSWORD_CHECK);
                break;
            default:
                break;
        }
    }

    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);
                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));
                }
                if (messageType.equals(Constants.WEBSOCKET_TYPE_AUTH_AUTO)) {
                    resultWsAuth(jsonObject);
                } else {

                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {

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

    /**
     * 알림 수신 여부 설정(알림 수신 여부를 설정 한다. (예 : 홈모드가 바뀔 때, 집이 빌 때)) 요청.
     */
    private void sendPutMemberPushNoti() {

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

                    resultPutMemberPushNoti(result);
                }
            });

            //공통 변수 입력
            httpSend.putMemberPushNoti(pushTypeModeChgYn);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                int tempMsgNum = 0;
                //                Dlog.v(alarmType);
                if (alarmType == ALRAM_MODE_ON) {
                    mAppConfig.setPush_Type_Mode_Chg_Yn("Y");
//                    tempMsgNum = R.string.MSG815;
                } else if (alarmType == ALRAM_MODE_OFF) {
                    mAppConfig.setPush_Type_Mode_Chg_Yn("N");
//                    tempMsgNum = R.string.MSG816;
                } else {

                }
//                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, tempMsgNum), Toast.LENGTH_SHORT);
                setDisp();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

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

    /**
     * 멤버 이미지 변경(멤버의 프로필 이미지를 수정) 요청.
     */
    private void sendPostMemberProfileImage() {

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

                    resultPostMemberProfileImage(result);
                }
            });

            //공통 변수 입력
            httpSend.postMemberProfileImage(Constants.KEY_IMAGE_FILE, mFileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (response.getStatusCode() == 200) {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());

                //회원 번호
                mFileName = mUtil.null2string(joResult.get(Constants.KEY_IMAGE_FILE));
                mUtil.setRefreshImage(mActivity, mFileName, R.id.ivMemberIcon);
                Dlog.i("mFileName = " + mFileName);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

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

    /**
     * 자동로그인  로그인 요청.
     */
    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);
    }

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

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

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

                        mAppConfig.setCtrtGroupId(ctrtGrpId);
                        mAppConfig.setCtrtGroupName(ctrtGrpName);
                        mAppConfig.setCtrtGroupGradeCode(gradeCode);
                        mAppConfig.setIsCtrtGroupHomehub(deviceExistYn);
//                mAppConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
                        mAppConfig.setPush_Type_Mode_Chg_Yn(pushTypeModeChgYn);
                    }
                }
                mAppConfig.setIsLogin(true);
                mAppConfig.setIsAutoLogin(mIsAutoLogin);
                mAppConfig.setSaveId(mIsSaveId);
                mAppConfig.setLoginId(mLoginId);
                mAppConfig.setLoginMemberId(memberId);
                mAppConfig.setMyImageUrl(profileImage);
                mAppConfig.setAuthToken(authToken);
                mAppConfig.setNickname(nickname);
                mAppConfig.setCustId(custId);
                mAppConfig.setQuiz(quiz);
                mAppConfig.setPhone(phone);

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

//                setFinish();
                setDisp();
            } else {
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
        loading = false;
        mSwipeRefreshLayout.setRefreshing(false);
    }

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

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

                    resultPutMember(result);
                }
            });

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

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

        try {
            if (response.getStatusCode() == 200) {

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

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

                newEmailId = "";
                if (joResult.has(Constants.KEY_NEW_EMAIL_ID)) {
                    newEmailId = mUtil.null2string(joResult.get(Constants.KEY_NEW_EMAIL_ID));
                }

                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 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.setLoginMemberId(memberId);
                //이메일 ID
                String emailId = mUtil.null2string(joResult.get(Constants.KEY_EMAIL_ID));
                mAppConfig.setLoginId(emailId);
                mAppConfig.setLogin_Pass("");
                Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
                mAppConfig.setIsAutoLogin(mIsAutoLogin);
                mAppConfig.setIsLogin(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);

                Dlog.v("mIsAutoLogin =" + mIsAutoLogin);
                sql = mSqlManager.qryInsertLoginInfo(emailId, 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.setCtrtGroupId(homegrpId);
//                mAppConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
                mAppConfig.setCtrtGroupName(homegrpName);
                mAppConfig.setCtrtGroupGradeCode(gradeCode);
                mAppConfig.setSelectHomehubDeviceId(homehubDeviceId);
                mAppConfig.setsSelect_Homegrp_Homehub_Conn_State(homehubConnState);
                mAppConfig.setsSelect_Homegrp_Homehub_Dongle_State(homehubDongleState);
                mAppConfig.setSelectServicehubAppId(servicehubApplicationId);
                mAppConfig.setsSelect_CtrtGroup_Homehub_Dongle_Online_Last_Datetime(deviceOnlineLastDatetime);

                loading = false;
                mSwipeRefreshLayout.setRefreshing(false);
                setDisp();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

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

    /**
     * 계정을 삭제해 회원 탈퇴를 처리한다.
     */
    private void sendDeleteMember() {

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

                    resultDeleteMember(result);
                }
            });

            //공통 변수 입력
            httpSend.deleteMember();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendDeleteMember()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultDeleteMember(Response response) {
        try {
            if (response.getStatusCode() == 200) {
//                JSONObject joResult = new JSONObject(response.getContent());
//                Dlog.v(joResult.toString());
                mUtil.callApp_Start(mActivity, "LOGOUT");

            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }

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

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG805:
                if (btnResult == 1) {
                    mAppConfig.setLogout(true);
                    mUtil.callApp_Start(mActivity, "LOGOUT");
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(type), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG910:
            case Constants.MSG911:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_D_MEMBER), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG908:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG937:
                if (1 == btnResult) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_D_MEMBER), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            default:
                break;
        }
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_SETTING_ADMIN_PASSWORD_CHK:
                    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_SETTING_PASSWORD_CHECK:
                case Constants.ACT_SETTING_NICKNAME_CHANGE:
                case Constants.ACT_SETTING_CELLPHONE_CHANGE:
                case Constants.ACT_SETTING_EMAIL_CHANGE:
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_WS_AUTH_AUTO), Constants.HANDLER_DELAY_MILLIS);
                    break;
                case Constants.ACT_IMAGE_SELECT:
                    mFileName = mUtil.null2string(data.getStringExtra(Constants.EXTRA_IMAGE_FILE_NAME));
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_MEMBER_PROFILE_IMAGE),
                            Constants.HANDLER_DELAY_MILLIS);
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                default:
                    break;
            }
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_WS_AUTH_AUTO:
//                    sendPutMember();
                    sendWsMemberAuthAuto();
                    break;
                case MSG_COM_P_MEMBER_PROFILE_IMAGE:
                    sendPostMemberProfileImage();
                    break;
                case MSG_COM_P_MEMBER_PUSH_NOTI:
                    sendPutMemberPushNoti();
                    break;
                case MSG_COM_D_MEMBER:
                    sendDeleteMember();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
