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

package com.ntels.kneet.v3.view;

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.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.db.DatabaseOpenHelper;
import com.ntels.kneet.v3.common.db.SQLManager;
import com.ntels.kneet.v3.common.gcm.support.KneetMessageLocalBroadCast;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.invitation.Invitation_List;

import org.json.JSONObject;

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

    /*툴바 관련*/
    private Toolbar toolbar;

    /*통신 관련*/
    private              int                                iType                  = 0;
    private static final int                                MSG_COM_P_MEMBER_LOGIN = 1;
    private static final int                                MSG_COM_G_MEMBER       = 2;

    /*공통*/
    private Activity       act;
    private AppConfig      appConfig;
    private Intent         intent;
    private Util         util              = new Util();
    private CustomDialog customDialog      = new CustomDialog();
    private SQLManager   sqlManager        = new SQLManager();
    private Boolean      bExitFlag         = false;    // 종료여부 묻기 플래그
    private Boolean      bAutoLogin        = false;
    private Boolean      bSaveId           = false;
    private Boolean      bAutoLogin1       = false;
    private String       sId               = "";
    private String       sPass             = "";
    private String       sPush_type_code   = "";

    @Override protected void onNewIntent(Intent saveIntent) {

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

    /**
     * <PRE>
     * 1. MethodName: onCreate
     * 2. ClassName :
     * 3. Comment   : onCreate
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        act = Login.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

        if ( savedInstanceState != null ) {
            bExitFlag = savedInstanceState.getBoolean(Constants.EXTRA_EXIT_FLAG, false);
        } else {
            intent = getIntent();
            bExitFlag = intent.getBooleanExtra(Constants.EXTRA_EXIT_FLAG, false);
            sPush_type_code = util.null2string(getIntent().getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
        }

        int iHeight = appConfig.getDisplayHeight();
        int iTempHeight = (int) (iHeight * 0.45);
        LinearLayout.LayoutParams paramView3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, iTempHeight);
        util.getView(act, R.id.llbody1).setLayoutParams(paramView3);
        util.getView(act, R.id.ivLogo).setLayoutParams(paramView3);

        LinearLayout.LayoutParams paramView4 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, iHeight - iTempHeight);
        util.getView(act, R.id.llbody1).setLayoutParams(paramView4);
        util.getView(act, R.id.btnLogin).setOnClickListener(this);
        util.getView(act, R.id.tvJoin).setOnClickListener(this);
        util.getView(act, R.id.tvPassFind).setOnClickListener(this);
        util.getView(act, R.id.llAutoLogin).setOnClickListener(this);

        util.getViewUnderline(act, R.id.tvJoin);
        util.getViewUnderline(act, R.id.tvPassFind);

        util.getEditText(act, R.id.edtId).setText("");
        util.getEditText(act, R.id.edtPass).setText("");

        util.setUserInfo(act);
        bAutoLogin = bAutoLogin1 = appConfig.getAutoLogin();
        Dlog.v("bAutoLogin =" + bAutoLogin);
        util.getView(act, R.id.llAutoLogin).setSelected(bAutoLogin1);
        if ( bAutoLogin1 ) {
            util.getView(act, R.id.llRoot).setVisibility(View.INVISIBLE);
            sId = appConfig.getLogin_Id();
            sPass = "";
            ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_MEMBER), 10);
        } else {
            util.getView(act, R.id.llAutoLogin).performClick();
        }
        util.setKeyboardHide(act, util.getLinearLayout(act, R.id.llSvbody));

    }

    @Override protected void onRestoreInstanceState(Bundle savedInstanceState) {

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

    @Override protected void onSaveInstanceState(Bundle outState) {

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

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    /**
     * <PRE>
     * 1. MethodName: onBackPressed
     * 2. ClassName :
     * 3. Comment   : onBackPressed
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onBackPressed() {

        if ( !mFlag ) {
            util.setShowToast(act, util.getString(act, R.string.MSG823), Toast.LENGTH_SHORT);
            mFlag = true;
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            setExit();
        }
    }

    Boolean mFlag = false;

    @Override protected void onDestroy() {

        super.onDestroy();
    }

    @Override public void setAnimFinish(String sVal) {

        super.setAnimFinish(sVal);
    }

    Handler mHandler = new Handler(new FinishHandlerCallBack());

    class FinishHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            if ( msg.what == 0 ) {
                mFlag = false;
            }
            return true;
        }
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llAutoLogin:
                if ( bAutoLogin ) {
                    bAutoLogin = false;
                } else {
                    bAutoLogin = true;
                }
                util.getView(act, R.id.llAutoLogin).setSelected(bAutoLogin);
                break;
            case R.id.btnLogin:
                sPass = "";
                sPass += util.getEditTextVal(act, R.id.edtPass).trim();
                sId = "";
                sId += util.getEditTextVal(act, R.id.edtId).trim();

                if ( !checkFormValid() ) {
                    util.setShowToast(act, util.getString(act, R.string.MSG802), Toast.LENGTH_SHORT);
                    return;
                }
                util.setVibrator(100);
                v.setEnabled(false);
                ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_P_MEMBER_LOGIN), 10);
                break;
            case R.id.tvJoin:
                intent = new Intent(act, Join_Chk.class);
                util.callActivityForResult(act, intent, Constants.ACT_JOIN_CHK);
                break;
            case R.id.tvPassFind:
                intent = new Intent(act, Reset_Password.class);
                util.callActivityForResult(act, intent, Constants.ACT_RESET_PASSWORD);
                break;
            default:
                break;
        }
    }

    private Boolean checkFormValid() {

        Boolean bCheck = true;

        if ( sId.trim().length() < 1 ) {
            bCheck = false;
        }
        if ( sPass.trim().length() < 1 ) {
            bCheck = false;
        }
        return bCheck;
    }

    /**
     * <PRE>
     * 1. MethodName: onResume
     * 2. ClassName :
     * 3. Comment   : onResume
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onResume() {

        super.onResume();
    }

    Handler ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            // TODO : 테스트 끝나면 주석 해제.
//            test_login();
            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_MEMBER_LOGIN:
                    send_P_member_login();
                    break;
                case MSG_COM_G_MEMBER:
                    send_G_member();
                    break;
                default:
                    break;
            }
            return true;
        }
    }

    private void send_P_member_login() {

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

                    result_P_member_login(result);
                }
            });
            httpSend.P_member_login(sId, sPass, appConfig.getService_Id(), Constants.OS_TYPE, appConfig.getUuid(), appConfig.getPush_Token(), util.getPhoneName(), util.getHostName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void send_G_member() {

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

                    result_P_member_login(result);
                }
            });

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

    /**
     * 로그인 시 토큰이 변경되는 문제로 임시 사용
     *
     */
    private void test_login() {
        try {
            //회원 번호
            String sMEMBER_ID = "24";
            //이메일 ID
            String sEMAIL_ID = "super810910@gmail.com";
            //서비스 ID
            String sSERVICE_ID = "30001";
            //국가 코드 (ex: KR)
            String sCOUNTRY_CODE = "KR";
            //타임존 ID
            String sTIMEZONE_ID = "210";
            //타임존 시간 (ex: +09:00)
            String sTIMEZONE = "+09:00";
            //언어 코드 (ex: en)
            String sLANG = "ko";
            //인증 토큰
            String sAUTH_TOKEN = "EAEAihAcWyMeIHW9Ye3LQETa+Mku5ZUOsJrPhz0uLt5ltNjbqglfbeTEWzj4YgGXz/Jru/8uQQfVP5DvIiwr8qYOscQVwR98";

            //회원이미지 추가
            /*String sIMAGE_FILE_NAME = "";
            if ( joResult.has(Constants.HTTP_image_file_name) ) {
                sIMAGE_FILE_NAME = util.null2string(joResult.get(Constants.HTTP_image_file_name));
                appConfig.setMy_Image_Url(sIMAGE_FILE_NAME);
            }*/
            //회원명
            String sNICKNAME = "최낙훈";
            /*if ( joResult.has(Constants.HTTP_nickname) ) {
                sNICKNAME = util.null2string(joResult.get(Constants.HTTP_nickname));
                appConfig.setNickname(sNICKNAME);
            }*/

            String sHTTP_NEW_EMAIL_ID = "";
            /*if ( joResult.has(Constants.HTTP_new_email_id) ) {
                sHTTP_NEW_EMAIL_ID = util.null2string(joResult.get(Constants.HTTP_new_email_id));
            }*/

            String sHTTP_TEMP_PASSWORD_YN = "N";
            /*if ( joResult.has(Constants.HTTP_temp_password_yn) ) {
                sHTTP_TEMP_PASSWORD_YN = util.null2string(joResult.get(Constants.HTTP_temp_password_yn));
            }*/
            appConfig.setTemp_Password_Yn(sHTTP_TEMP_PASSWORD_YN);

            String sPUSH_TYPE_MODE_CHG_YN = "Y";
            String sPUSH_TYPE_PRSNC_CHG_YN = "Y";

            String sHTTP_invitations_count = "0";
            /*if ( joResult.has(Constants.HTTP_invitations_count) ) {
                sHTTP_invitations_count = util.null2string(joResult.get(Constants.HTTP_invitations_count));
            }*/

            String sHTTP_homegrp_id = "1";
            /*if ( joResult.has(Constants.HTTP_homegrp_id) ) {
                sHTTP_homegrp_id = util.null2string(joResult.get(Constants.HTTP_homegrp_id));
            }*/

            /*String sHTTP_homegrp_image_file_name = "";
            if ( joResult.has(Constants.HTTP_homegrp_image_file_name) ) {
                sHTTP_homegrp_image_file_name = util.null2string(joResult.get(Constants.HTTP_homegrp_image_file_name));
            }*/

            String sHTTP_homegrp_name = "나의집";
            /*if ( joResult.has(Constants.HTTP_homegrp_name) ) {
                sHTTP_homegrp_name = util.null2string(joResult.get(Constants.HTTP_homegrp_name));
            }*/

            String sHTTP_grade_code = "MAS";
            /*if ( joResult.has(Constants.HTTP_grade_code) ) {
                sHTTP_grade_code = util.null2string(joResult.get(Constants.HTTP_grade_code));
            }*/

            String sHTTP_homehub_device_id = "D00000000020";
            /*if ( joResult.has(Constants.HTTP_homehub_device_id) ) {
                sHTTP_homehub_device_id = util.null2string(joResult.get(Constants.HTTP_homehub_device_id));
            }*/



            String sHTTP_homehub_online_state = "ON";
            /*if ( joResult.has(Constants.HTTP_homehub_online_state) ) {
                sHTTP_homehub_online_state = util.null2string(joResult.get(Constants.HTTP_homehub_online_state));
            }*/

            String sHTTP_servicehub_application_id = "A19636184968";

            appConfig.setLogin_Member_Id(sMEMBER_ID);
            appConfig.setLogin_Id(sEMAIL_ID);
            if ( sHTTP_TEMP_PASSWORD_YN.equals("Y") ) {
                appConfig.setLogin_Pass(sPass);
            } else {
                appConfig.setLogin_Pass("");
            }
            appConfig.setAutoLogin(bAutoLogin);
            appConfig.setLogin(true);

            //공통 변수 입력
            appConfig.setAuth_Token(sAUTH_TOKEN);

            //db 입력작업
            SQLiteDatabase db = DatabaseOpenHelper.getInstance(act).getWritableDatabase();
            String sSql = "";
            sSql = "";
            sSql = sqlManager.QryDelLoginInfo();
            db.execSQL(sSql);

            sSql = "";
            Dlog.v("bAutoLogin =" + bAutoLogin);
            sSql = sqlManager.QryInsertLoginInfo(sEMAIL_ID, sAUTH_TOKEN, bSaveId, bAutoLogin, appConfig.getManualNotView(), appConfig.getPush());
            db.execSQL(sSql);
            db.close();

            appConfig.setPush_Type_Mode_Chg_Yn(sPUSH_TYPE_MODE_CHG_YN);
            appConfig.setPush_Type_Prsnc_Chg_Yn(sPUSH_TYPE_PRSNC_CHG_YN);
            appConfig.setInvitations_Count(sHTTP_invitations_count);
            appConfig.setSelect_Homegrp_Id(sHTTP_homegrp_id);
//            appConfig.setSelect_Homegrp_Icon(sHTTP_homegrp_image_file_name);
            appConfig.setSelect_Homegrp_Name(sHTTP_homegrp_name);
            appConfig.setSelect_Homegrp_Grade_Code(sHTTP_grade_code);
            appConfig.setSelect_Homegrp_Homehub_Device_Id(sHTTP_homehub_device_id);
            appConfig.setSelect_Homegrp_Homehub_Online_State(sHTTP_homehub_online_state);
            appConfig.setsSelect_Servicehub_App_Id(sHTTP_servicehub_application_id);

            if ( util.str2int(sHTTP_invitations_count) > 0 ) {
                Intent intent = new Intent(act, Invitation_List.class);
                util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_LIST);
                return;
            }

            setFinish();
        } catch (Exception ex) {
            ex.printStackTrace();
            util.getView(act, R.id.llRoot).setVisibility(View.VISIBLE);
            customDialog.MsgAlert(act, Constants.MSG807);
        }

        try {
            util.getButton(act, R.id.btnLogin).setEnabled(true);
        } catch (Exception ex) {

        }
    }

    private void result_P_member_login(Response rpResult) {

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

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

                //회원 번호
                String sMEMBER_ID = util.null2string(joResult.get(Constants.HTTP_member_id));
                //이메일 ID
                String sEMAIL_ID = util.null2string(joResult.get(Constants.HTTP_email_id));
                //서비스 ID
                String sSERVICE_ID = util.null2string(joResult.get(Constants.HTTP_service_id));
                //국가 코드 (ex: KR)
                String sCOUNTRY_CODE = util.null2string(joResult.get(Constants.HTTP_country_code));
                //타임존 ID
                String sTIMEZONE_ID = util.null2string(joResult.get(Constants.HTTP_timezone_id));
                //타임존 시간 (ex: +09:00)
                String sTIMEZONE = util.null2string(joResult.get(Constants.HTTP_timezone));
                //언어 코드 (ex: en)
                String sLANG = util.null2string(joResult.get(Constants.HTTP_lang));
                //인증 토큰
                String sAUTH_TOKEN = util.null2string(joResult.get(Constants.HTTP_auth_token));
                //회원이미지 추가
                String sIMAGE_FILE_NAME = "";
                if ( joResult.has(Constants.HTTP_image_file_name) ) {
                    sIMAGE_FILE_NAME = util.null2string(joResult.get(Constants.HTTP_image_file_name));
                    appConfig.setMy_Image_Url(sIMAGE_FILE_NAME);
                }
                //회원명
                String sNICKNAME = "";
                if ( joResult.has(Constants.HTTP_nickname) ) {
                    sNICKNAME = util.null2string(joResult.get(Constants.HTTP_nickname));
                    appConfig.setNickname(sNICKNAME);
                }

                String sHTTP_NEW_EMAIL_ID = "";
                if ( joResult.has(Constants.HTTP_new_email_id) ) {
                    sHTTP_NEW_EMAIL_ID = util.null2string(joResult.get(Constants.HTTP_new_email_id));
                }

                String sHTTP_TEMP_PASSWORD_YN = "";
                if ( joResult.has(Constants.HTTP_temp_password_yn) ) {
                    sHTTP_TEMP_PASSWORD_YN = util.null2string(joResult.get(Constants.HTTP_temp_password_yn));
                }
                appConfig.setTemp_Password_Yn(sHTTP_TEMP_PASSWORD_YN);

                String sPUSH_TYPE_MODE_CHG_YN = util.null2string(joResult.get(Constants.HTTP_push_type_mode_chg_yn));
                String sPUSH_TYPE_PRSNC_CHG_YN = util.null2string(joResult.get(Constants.HTTP_push_type_prsnc_chg_yn));

                String sHTTP_invitations_count = "";
                if ( joResult.has(Constants.HTTP_invitations_count) ) {
                    sHTTP_invitations_count = util.null2string(joResult.get(Constants.HTTP_invitations_count));
                }

                String sHTTP_homegrp_id = "";
                if ( joResult.has(Constants.HTTP_homegrp_id) ) {
                    sHTTP_homegrp_id = util.null2string(joResult.get(Constants.HTTP_homegrp_id));
                }

                String sHTTP_homegrp_image_file_name = "";
                if ( joResult.has(Constants.HTTP_homegrp_image_file_name) ) {
                    sHTTP_homegrp_image_file_name = util.null2string(joResult.get(Constants.HTTP_homegrp_image_file_name));
                }

                String sHTTP_homegrp_name = "";
                if ( joResult.has(Constants.HTTP_homegrp_name) ) {
                    sHTTP_homegrp_name = util.null2string(joResult.get(Constants.HTTP_homegrp_name));
                }

                String sHTTP_grade_code = "";
                if ( joResult.has(Constants.HTTP_grade_code) ) {
                    sHTTP_grade_code = util.null2string(joResult.get(Constants.HTTP_grade_code));
                }

                String sHTTP_homehub_device_id = "";
                if ( joResult.has(Constants.HTTP_homehub_device_id) ) {
                    sHTTP_homehub_device_id = util.null2string(joResult.get(Constants.HTTP_homehub_device_id));
                }

//                String sHTTP_homehub_online_state = "";
//                if ( joResult.has(Constants.HTTP_homehub_online_state) ) {
//                    sHTTP_homehub_online_state = util.null2string(joResult.get(Constants.HTTP_homehub_online_state));
//                }

                String sHTTP_homehub_conn_state = "";
                if ( joResult.has(Constants.HTTP_device_conn) ) {
                    sHTTP_homehub_conn_state = util.null2string(joResult.get(Constants.HTTP_device_conn));
                }

                String sHTTP_homehub_dongle_state = "";
                if ( joResult.has(Constants.HTTP_device_online) ) {
                    sHTTP_homehub_dongle_state = util.null2string(joResult.get(Constants.HTTP_device_online));
                }

                String sHTTP_servicehub_application_id = "";
                if ( joResult.has(Constants.HTTP_servicehub_app_id) ) {
                    sHTTP_servicehub_application_id = util.null2string(joResult.get(Constants.HTTP_servicehub_app_id));
                }

                appConfig.setLogin_Member_Id(sMEMBER_ID);
                appConfig.setLogin_Id(sEMAIL_ID);
                if ( sHTTP_TEMP_PASSWORD_YN.equals("Y") ) {
                    appConfig.setLogin_Pass(sPass);
                } else {
                    appConfig.setLogin_Pass("");
                }
                appConfig.setAutoLogin(bAutoLogin);
                appConfig.setLogin(true);

                //공통 변수 입력
                appConfig.setAuth_Token(sAUTH_TOKEN);

                //db 입력작업
                SQLiteDatabase db = DatabaseOpenHelper.getInstance(act).getWritableDatabase();
                String sSql = "";
                sSql = "";
                sSql = sqlManager.QryDelLoginInfo();
                db.execSQL(sSql);

                sSql = "";
                Dlog.v("bAutoLogin =" + bAutoLogin);
                sSql = sqlManager.QryInsertLoginInfo(sEMAIL_ID, sAUTH_TOKEN, bSaveId, bAutoLogin, appConfig.getManualNotView(), appConfig.getPush());
                db.execSQL(sSql);
                db.close();

                appConfig.setPush_Type_Mode_Chg_Yn(sPUSH_TYPE_MODE_CHG_YN);
                appConfig.setPush_Type_Prsnc_Chg_Yn(sPUSH_TYPE_PRSNC_CHG_YN);
                appConfig.setInvitations_Count(sHTTP_invitations_count);
                appConfig.setSelect_Homegrp_Id(sHTTP_homegrp_id);
                appConfig.setSelect_Homegrp_Icon(sHTTP_homegrp_image_file_name);
                appConfig.setSelect_Homegrp_Name(sHTTP_homegrp_name);
                appConfig.setSelect_Homegrp_Grade_Code(sHTTP_grade_code);
                appConfig.setSelect_Homegrp_Homehub_Device_Id(sHTTP_homehub_device_id);
                appConfig.setsSelect_Homegrp_Homehub_Conn_State(sHTTP_homehub_conn_state);
                appConfig.setsSelect_Homegrp_Homehub_Dongle_State(sHTTP_homehub_dongle_state);
//                appConfig.setSelect_Homegrp_Homehub_Online_State(sHTTP_homehub_online_state);
                appConfig.setsSelect_Servicehub_App_Id(sHTTP_servicehub_application_id);

                if ( util.str2int(sHTTP_invitations_count) > 0 ) {
                    Intent intent = new Intent(act, Invitation_List.class);
                    util.callActivityForResultNoAnim(act, intent, Constants.ACT_INVITATION_LIST);
                    return;
                }

                setFinish();
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));

                if ( sERR_CODE.equals("401") ) {
                    util.getView(act, R.id.llRoot).setVisibility(View.VISIBLE);
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                } else if ( sERR_CODE.equals("401-101") ) {
                    util.getView(act, R.id.llRoot).setVisibility(View.VISIBLE);
                    customDialog.MsgAlert(act, Constants.MSG828, sId, R.string.MSG_TITLE_001);
                } else if ( sERR_CODE.equals("401-103") ) {
                    String sNICKNAME = util.null2string(joResult.get(Constants.HTTP_nickname));
                    Intent intent = new Intent(act, Login_New_Device.class);
                    intent.putExtra(Constants.EXTRA_EMAIL_ID, sId);
                    intent.putExtra(Constants.EXTRA_NICKNAME, sNICKNAME);
                    util.callActivityForResult(act, intent, Constants.ACT_LOGIN_NEW_DEVICE);
                } else {
                    util.getView(act, R.id.llRoot).setVisibility(View.VISIBLE);
                    customDialog.MsgAlert(act, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            util.getView(act, R.id.llRoot).setVisibility(View.VISIBLE);
            customDialog.MsgAlert(act, Constants.MSG807);
        }

        try {
            util.getButton(act, R.id.btnLogin).setEnabled(true);
        } catch (Exception ex) {

        }
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        Boolean bReload_Flag = false;
        if ( resultCode == RESULT_OK ) {
            switch (requestCode) {
                case Constants.ACT_ERROR_PAGE:
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                    break;
                case Constants.ACT_JOIN:
                    //setFinish();
                    break;
                case Constants.ACT_LOGIN_NEW_DEVICE:
                    bReload_Flag = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if ( bReload_Flag ) {
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_MEMBER), 10);
                    } else {
                        setFinish();
                    }
                    break;
                case Constants.ACT_LOGIN_DEVICE_OVER:
                    String sEMAIL_ID = util.null2string(data.getStringExtra(Constants.EXTRA_EMAIL_ID));
                    String sNICKNAME = util.null2string(data.getStringExtra(Constants.EXTRA_NICKNAME));
                    String sHTTP_device_sn = util.null2string(data.getStringExtra(Constants.HTTP_device_sn));
                    intent = new Intent(act, Login_New_Device.class);
                    intent.putExtra(Constants.EXTRA_EMAIL_ID, sEMAIL_ID);
                    intent.putExtra(Constants.EXTRA_NICKNAME, sNICKNAME);
                    intent.putExtra(Constants.HTTP_device_sn, sHTTP_device_sn);
                    util.callActivityForResultNoAnim(act, intent, Constants.ACT_LOGIN_NEW_DEVICE);
                    break;
                case Constants.ACT_INVITATION_LIST:
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_MEMBER), 10);
                    break;
                default:
                    break;
            }
        } else {
            if ( appConfig.getGoErr() ) {
                setExit();
            } else {
                switch (requestCode) {
                    case Constants.ACT_INVITATION_LIST:
                        setFinish();
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Override public void resultCustomDialogResponse(int iMsgID, int iBtnResult) {

        switch (iMsgID) {
            case Constants.MSG801:
                if ( iBtnResult == 1 ) {
                    Dlog.v("jino test");
                }
                break;
            case Constants.MSG804:
                if ( iBtnResult == 1 ) {
                    setExit();
                }
                break;
            case Constants.MSG807:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessageDelayed(ComHandler.obtainMessage(iType), 10);
                } else {
                    setExit();
                }
                break;
            default:
                break;
        }
    }

    private void setFinish() {
        // 종료후 메인으로 가기
        Intent intent = new Intent(act, Main.class);
        intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, "");
        util.callActivityNoAnim(act, intent);

        setFinishLoading();
    }

    public void setFinishLoading() {

        int iInterval = 1000;
        finishhandler.sendEmptyMessageDelayed(0, iInterval); // ms,
    }

    private Handler finishhandler = new Handler(new Handler.Callback() {
        @Override public boolean handleMessage(Message message) {

            if ( !appConfig.getMain() ) {
                setFinishLoading();
            } else {
                finish();
            }
            return false;
        }
    });
    private void setExit() {

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