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

package com.ntels.kneet.v3.view;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
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.Main_Interface;
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.mdns.MdnsDiscovery;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.websocket.WebSocketService;
import com.ntels.kneet.v3.common.widget.CustomActionBarActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.homemember.Fragment_HomeMember;
import com.ntels.kneet.v3.view.invitation.Invitation_List;
import com.ntels.kneet.v3.view.main_more.Main_More;
import com.ntels.kneet.v3.view.main_more.Setting_Password_Change;
import com.ntels.kneet.v3.view.rules.Fragment_Rules;
import com.ntels.kneet.v3.view.things.Fragment_Things;
import com.ntels.kneet.v3.view.things.Things_Homehub_Guide;
import com.ntels.kneet.v3.view.things.Things_Homehub_Guide_Intro;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Main extends CustomActionBarActivity implements View.OnClickListener,
                                                             CustomDialog.OnMsgAlterToResult,
                                                             Main_Interface {

    private AppConfig appConfig;
    private SQLManager sqlManager = new SQLManager();
    private Intent          intent;
    private ScheduledFuture scheduledFuture;
    private Util         util         = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private Activity actMain;
    private int iType             = 0;
    private int iFragmentPosition = 0;

    private Fragment fragment;
    private static final int MSG_MAIN_INIT                       = 1;
    private static final int MSG_COM_G_MEMBER_LOGOUT             = 2;
    private static final int MSG_COM_G_MEMBER                    = 3;
//    private static final int MSG_COM_G_DEVICES_HOMEHUB_STATUS    = 4;
    private static final int MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID = 5;

    private String  sPush_type_code            = "";
    private Boolean bSaveId                    = false;
    private Boolean bActivityOnDestroyedRaised = false;
    private Boolean bPollingCondition          = false;

    private Intent webSocketServiceIntent;

    @Override protected void onNewIntent(Intent saveIntent) {

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

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

            Boolean bTEmp = saveIntent.getBooleanExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE, false);
            Dlog.v("bTEmp", bTEmp);
            if ( iFragmentPosition == Constants.MENU_THINGS ) {
                Fragment_Things fragment = (Fragment_Things) getFragmentManager().findFragmentById(R.id.frame_container);
                fragment.setHomeHubStateAll();
            }
            if ( iFragmentPosition == Constants.MENU_HOMEMEMBER ) {
                Fragment_HomeMember fragment = (Fragment_HomeMember) getFragmentManager().findFragmentById(R.id.frame_container);
                fragment.setHomeHubStateAll();
            }
            if ( iFragmentPosition == Constants.MENU_RULES ) {
                Fragment_Rules fragment = (Fragment_Rules) getFragmentManager().findFragmentById(R.id.frame_container);
                fragment.setHomeHubStateAll();
            }
        }
    }

    @Override protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        actMain = Main.this;
        appConfig = (AppConfig) actMain.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        Dlog.v("appConfig.getIntro()=" + appConfig.getIntro());

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

        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_MAIN_INIT), 10);

//        setHomeHubPolling();
        appConfig.setMain(true);

        webSocketServiceIntent = new Intent(this, WebSocketService.class);
        startService(webSocketServiceIntent);
    }

    /*private void setHomeHubPolling() {

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

        scheduledFuture = scheduler.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.MINUTES);
    }*/

    /*Runnable runnable = new Runnable() {
        public void run() {

            Dlog.v("bPollingCondition", bPollingCondition);
            Dlog.v("bActivityOnDestroyedRaised", bActivityOnDestroyedRaised);

            if ( bPollingCondition ) {
                scheduledFuture.cancel(false);
            }

            if ( !bActivityOnDestroyedRaised ) {
                if ( appConfig.getSelect_Homegrp_Id().equals("") ) {
                    return;
                }
                if ( appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("") ) {
                    return;
                }
                send_G_devices_homehub_status();
            }
        }
    };*/

    private void setInit() {

        util.getView(actMain, R.id.llMainNavi1).setOnClickListener(this);
        util.getView(actMain, R.id.llMainNavi2).setOnClickListener(this);
        util.getView(actMain, R.id.llMainNavi3).setOnClickListener(this);
        util.getView(actMain, R.id.llMainNavi4).setOnClickListener(this);
        displayView(Constants.MENU_THINGS);
        if ( appConfig.getTemp_Password_Yn().equals("Y") ) {
            customDialog.MsgAlert(actMain, Constants.MSG892);
        }
    }

    @Override public void onClick(View v) {

        switch (v.getId()) {
            case R.id.llMainNavi1:
                displayView(Constants.MENU_THINGS);
                break;
            case R.id.llMainNavi2:
                displayView(Constants.MENU_RULES);
                break;
            case R.id.llMainNavi3:
                displayView(Constants.MENU_HOMEMEMBER);
                break;
            case R.id.llMainNavi4:
                intent = new Intent(actMain, Main_More.class);
                util.callActivityForResult(actMain, intent, Constants.ACT_MAIN_MORE, Constants.CHANGE_EVENT_BOTTOM_BOTTOM);
                break;
            default:
                break;
        }
    }

    private void SelectMainNavi(View v) {

        util.getView(actMain, R.id.llMainNavi1).setSelected(false);
        util.getView(actMain, R.id.llMainNavi2).setSelected(false);
        util.getView(actMain, R.id.llMainNavi3).setSelected(false);
        v.setSelected(true);
    }

    @Override public boolean onPrepareOptionsMenu(Menu menu) {

        return super.onPrepareOptionsMenu(menu);
    }

    private void displayView(int position) {

        int iTempPosition = iFragmentPosition;
        Boolean bMenu = false;
        Boolean bMenuClose = true;
        iFragmentPosition = position;
        switch (position) {
            case Constants.MENU_THINGS:
                SelectMainNavi(util.getView(actMain, R.id.llMainNavi1));
                fragment = new Fragment_Things();
                bMenu = true;
                break;
            case Constants.MENU_RULES:
                SelectMainNavi(util.getView(actMain, R.id.llMainNavi2));
                fragment = new Fragment_Rules();
                bMenu = true;
                break;
            case Constants.MENU_HOMEMEMBER:
                SelectMainNavi(util.getView(actMain, R.id.llMainNavi3));
                fragment = new Fragment_HomeMember();
                bMenu = true;
                break;
            default:
                break;
        }
        if ( fragment != null ) {
            FragmentManager fmBody = getFragmentManager();
            fmBody.beginTransaction().setCustomAnimations(R.anim.left_in, R.anim.right_out);
            fmBody.beginTransaction().replace(R.id.frame_container, fragment).commit();
        }
    }

    @Override protected void onDestroy() {

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

        if ( scheduledFuture != null ) {
            scheduledFuture.cancel(false);
            bActivityOnDestroyedRaised = true;
        }

        stopService(webSocketServiceIntent);
    }

    @Override public void setTitle(CharSequence title) {

    }

    @Override public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

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

        try {
            if ( resultCode == RESULT_OK ) {
                switch (requestCode) {
                    case Constants.ACT_LOGIN:
                        displayView(Constants.MENU_DASHBOARD);
                        break;
                    case Constants.ACT_INVITATION_LIST:
                        ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_MEMBER), 10);
                        break;
                    case Constants.ACT_HOME_SELECT_POP:
                        displayView(Constants.MENU_DASHBOARD);
                        break;
                    case Constants.ACT_THINGS_GROUP_ADD:
                        break;
                    case Constants.ACT_THINGS_HOMEHUB_GUIDE:
                        Intent intent = new Intent(actMain, Home_Start.class);
                        util.callActivityForResultNoAnim(actMain, intent, Constants.ACT_HOME_START);
                        break;
                    case Constants.ACT_HOME_START:
                        util.callApp_Start(actMain, "HOME_RELOAD");
                        break;
                    case Constants.ACT_MAIN_MORE:
                        displayView(iFragmentPosition);
                        break;
                    default:
                        fragment = getFragmentManager().findFragmentById(R.id.frame_container);
                        if ( fragment != null ) {
                            fragment.onActivityResult(requestCode, resultCode, data);
                        }
                        break;
                }
            } else {
                switch (requestCode) {
                    case Constants.ACT_HOME_START:
                        displayView(iFragmentPosition);
                        break;
                    case Constants.ACT_MAIN_MORE:
                        displayView(iFragmentPosition);
                        break;
                    default:
                        fragment = getFragmentManager().findFragmentById(R.id.frame_container);
                        if ( fragment != null ) {
                            fragment.onActivityResult(requestCode, resultCode, data);
                        }
                        break;
                }
                if ( appConfig.getGoErr() ) {
                    setExit();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

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

    Boolean mFlag = false;

    // BACK키 핸들러
    Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {

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

    @Override public void onLogout() {

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

    @Override public void onMenuFadeIn() {

    }

    @Override public void onMenuFadeOut() {

    }

    @Override public void onTitleFadeIn(Boolean bAnim) {

    }

    @Override public void onTitleFadeOut(Boolean bAnim) {

    }

    @Override public void onMenuClick() {

    }

    @Override public void onGotoMenu(int iMenu) {

        displayView(iMenu);
    }

    @Override public void onPrograssON() {
        // dialog_show();
    }

    @Override public void onPrograssOFF() {
        // dialog_dismiss();
    }

    @Override public void onMenuRefresh() {

    }

    @Override public void onRuleRegistClick() {

    }
    @Override public void onHomehubStart() {

//        Intent intent = new Intent(actMain, Things_Homehub_Guide_Intro.class);
        Intent intent = new Intent(actMain, Things_Homehub_Guide.class);
        util.callActivityForResultNoAnim(actMain, intent, Constants.ACT_THINGS_HOMEHUB_GUIDE);
    }
    @Override public void onHomeMemberWidthdraw() {

        customDialog.MsgAlert(actMain, Constants.MSG835, R.string.MSG_TITLE_002);
    }

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

        switch (iMsgID) {

            case Constants.MSG998:
                util.callApp_Start(actMain, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(actMain, "HOME_RELOAD");
                break;
            case Constants.MSG805:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessage(ComHandler.obtainMessage(MSG_COM_G_MEMBER_LOGOUT));
                }
                break;
            case Constants.MSG835:
                if ( iBtnResult == 1 ) {
                    ComHandler.sendMessage(ComHandler.obtainMessage(MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID));
                }
                break;
            case Constants.MSG892:
                appConfig.setTemp_Password_Yn("");
                appConfig.setLogin_Pass("");
                if ( iBtnResult == 1 ) {
                    intent = new Intent(actMain, Setting_Password_Change.class);
                    intent.putExtra(Constants.EXTRA_PASSWORD, appConfig.getLogin_Pass());
                    util.callActivityForResultNoAnim(actMain, intent, Constants.ACT_SETTING_PASSWORD_CHANGE);
                }
                break;
            default:
                break;
        }
    }

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_MEMBER_LOGOUT:
                    send_G_member_logout();
                    break;
                case MSG_COM_G_MEMBER:
                    send_G_member();
                    break;
                case MSG_MAIN_INIT:
                    setInit();
                    break;
                /*case MSG_COM_G_DEVICES_HOMEHUB_STATUS:
                    send_G_devices_homehub_status();
                    break;*/
                case MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID:
                    send_D_homegrp_members_member_id();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_D_homegrp_members_member_id
     * 2. ClassName :
     * 3. Comment   : [Send][DELETE]홈그룹 (자진) 탈퇴(일반 등급의 홈그룹 멤버를 홈그룹에서 자진 탈퇴 처리한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_D_homegrp_members_member_id() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(actMain);

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

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

    /**
     * <PRE>
     * 1. MethodName: result_D_homegrp_members_member_id
     * 2. ClassName :
     * 3. Comment   : [Result][DELETE]홈그룹 (자진) 탈퇴(일반 등급의 홈그룹 멤버를 홈그룹에서 자진 탈퇴 처리한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_D_homegrp_members_member_id(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                util.callApp_Start(actMain, "HOME_RELOAD");
            } 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") ) {
                    customDialog.MsgAlert(actMain, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(actMain, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(actMain, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(actMain, Constants.MSG807);
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_G_devices_homehub_status
     * 2. ClassName :
     * 3. Comment   : [Send][GET]홈허브 장치 상태 정보 조회(현재 홈그룹에 등록된 홈허브의 상태 정보를 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    /*private void send_G_devices_homehub_status() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(actMain, false);

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

                    result_G_devices_homehub_status(result);
                }
            });
            if ( appConfig.getSelect_Homegrp_Id().equals("") ) {
                return;
            }
            if ( appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("") ) {
                return;
            }
            httpSend.G_devices_homehub_status();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }*/

    /**
     * <PRE>
     * 1. MethodName: result_G_devices_homehub_status
     * 2. ClassName :
     * 3. Comment   : [Result][GET]홈허브 장치 상태 정보 조회(현재 홈그룹에 등록된 홈허브의 상태 정보를 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
   /* private void result_G_devices_homehub_status(Response rpResult) {

        try {
            if ( rpResult.getStatusCode() == 200 ) {
                String sTempHomehub_State = appConfig.getSelect_Homegrp_Homehub_Online_State();
                JSONObject joResult = new JSONObject(rpResult.getContent());
                String sHTTP_online_state = util.null2string(joResult.get(Constants.HTTP_online_state));
                String sHTTP_create_datetime = util.null2string(joResult.get(Constants.HTTP_create_datetime));

                appConfig.setSelect_Homegrp_Homehub_Online_State(sHTTP_online_state);
                if ( !sTempHomehub_State.equals(sHTTP_online_state) ) {
                    //상태가 변경되었을때만 브로드캐스트를 날려준다
                    Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                    intent.putExtra(KneetMessageLocalBroadCast.INTENT_NAME_TYPE, KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE);
                    intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE, true);
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                }
            } 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") ) {
                    if ( appConfig.getSelect_Homegrp_Id().equals("") ) {
                        return;
                    }
                    if ( appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("") ) {
                        return;
                    }
                    customDialog.MsgAlert(actMain, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(actMain, Constants.MSG997, sERR_MSG);
                } else {
                    if ( sERR_CODE.equals("400-404") ) {
                        appConfig.setSelect_Homegrp_Homehub_Online_State("");
                        //상태가 변경되었을때만 브로드캐스트를 날려준다
                        Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                        intent.putExtra(KneetMessageLocalBroadCast.INTENT_NAME_TYPE, KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE);
                        intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE, true);
                        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }*/

    private void send_G_member() {

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

                    result_G_member(result);
                }
            });

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

    private void result_G_member(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_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_homehub_online_state = "";
                if ( joResult.has(Constants.HTTP_homehub_online_state) ) {
                    sHTTP_homehub_online_state = util.null2string(joResult.get(Constants.HTTP_homehub_online_state));
                }*/

                appConfig.setLogin_Member_Id(sMEMBER_ID);
                appConfig.setLogin_Id(sEMAIL_ID);
                appConfig.setLogin(true);

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

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

                sSql = "";
                sSql = sqlManager.QryInsertLoginInfo(sEMAIL_ID, sAUTH_TOKEN, bSaveId, appConfig.getAutoLogin(), 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.setSelect_Homegrp_Homehub_Online_State("ON");

                if ( sPush_type_code.equals("HOME_MEM_INV") ) {
                    //    홈 초대 받음
                    if ( util.str2int(sHTTP_invitations_count) > 0 ) {
                        Intent intent = new Intent(actMain, Invitation_List.class);
                        util.callActivityForResultNoAnim(actMain, intent, Constants.ACT_INVITATION_LIST);
                        return;
                    } else {
                        displayView(Constants.MENU_THINGS);
                    }
                } else if ( sPush_type_code.equals("HOME_MEM_BAN") ) {
                    //    홈 강퇴 받음
                    displayView(Constants.MENU_THINGS);
                } else if ( sPush_type_code.equals("HOME_DEL") ) {
                    //    홈 삭제
                    displayView(Constants.MENU_THINGS);
                } else if ( sPush_type_code.equals("HOMEHUB_DEL") ) {
                    //    홈 허브가 삭제됨
                    displayView(Constants.MENU_THINGS);
                } else if ( sPush_type_code.equals("DVC_OWN_CHG") ) {
                    //    장치 소유주 변경 알림
                    displayView(Constants.MENU_THINGS);
                } else if ( sPush_type_code.equals("MEM_ALL_OUT") ) {
                    //    멤버 All out 시
                    displayView(Constants.MENU_THINGS);
                } else if ( sPush_type_code.equals("MEM_ANY_IN") ) {
                    //    멤버 Any in 시
                    displayView(Constants.MENU_THINGS);
                } else if ( sPush_type_code.equals("HOME_RELOAD") ) {
                    //    홈 멤버 정보 재조회 알림
                    displayView(Constants.MENU_THINGS);
                }
                sPush_type_code = "";
            } 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") ) {
                    customDialog.MsgAlert(actMain, Constants.MSG998, sERR_MSG);
                } else if ( sERR_CODE.equals("401-106") ) {
                    customDialog.MsgAlert(actMain, Constants.MSG997, sERR_MSG);
                } else {
                    customDialog.MsgAlert(actMain, Constants.MSG000, sERR_MSG);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.MsgAlert(actMain, Constants.MSG807);
        }
    }

    private void send_G_member_logout() {

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

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

    private void result_G_member_logout(Response rpResult) {

        appConfig.setAuth_Token("");
        appConfig.setAutoLogin(false);
        SQLiteDatabase db = DatabaseOpenHelper.getInstance(actMain).getWritableDatabase();
        String sSql = "";
        sSql = sqlManager.QryUpdateLoginInfo_AutoLogin(false);
        db.execSQL(sSql);

        appConfig.setLogin_Pass("");

        if ( appConfig.getAutoLogin() ) {
            sSql = "";
            sSql = sqlManager.QryUpdateLoginInfo_Login_Pass("");
            db.execSQL(sSql);
        }

        appConfig.setLogin(false);
        appConfig.setMain(false);
        Dlog.v(appConfig.getIntro());
        intent = new Intent(actMain, Login.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        util.callActivityNoAnim(actMain, intent);
        finish();
    }

    private void setExit() {

        Dlog.v("setExit()");
        appConfig.setIntro(false);
        appConfig.setGoErr(false);
        appConfig.setMain(false);
        if ( webSocketServiceIntent != null ) {
            stopService(webSocketServiceIntent);
        }
        finish();
        return;
    }
}
