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

package com.ntels.onecable.admin.view;

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.broadcast.KneetMessageLocalBroadCast;
import com.ntels.onecable.admin.common.c_interface.MainInterface;
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.handler.BackPressCloseHandler;
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.LogUtil;
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.admin.FragmentAdmin;
import com.ntels.onecable.admin.view.customer.CustomerConnection;
import com.ntels.onecable.admin.view.customer.FragmentCustomer;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.ntels.onecable.admin.view.dialog.DialogSpinner;
import com.ntels.onecable.admin.view.install.FragmentInstall;
import com.ntels.onecable.admin.view.mainmore.SettingPasswordChange;
import com.ntels.onecable.admin.view.things.FragmentThings;
import com.ntels.onecable.admin.view.things.ThingsHomehubGuide;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;

import java.util.ArrayList;
import java.util.HashMap;

import static com.ntels.onecable.admin.R.id.btnCustomerConnect;
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.broadcast.DefaultLocalBroadCast.INTENT_NAME_TYPE;

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

    private static final String TAG = Main.class.getSimpleName();

    private static final int MSG_MAIN_INIT = 1;
    private static final int MSG_COM_G_MEMBER_LOGOUT = 2;
    private static final int MSG_COM_G_MEMBER = 3;
    private static final int MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID = 4;
    private static final int MSG_COM_WS_DEVICE_ALIVE = 5;
    private static final int MSG_COM_G_CUSTOMER_CTRT = 6;
    Handler updateTimeHandler = new Handler();
    private int mTotalCheckTime = 1000 * 60 * 60 * 2;
    private long mStartCheckTime = 0;
    private Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private BackPressCloseHandler mBackPressCloseHandler;
    private AppConfig mAppConfig;
    private SqlManager mSqlManager = new SqlManager();
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private Activity mActivity;
    private int mType = 0;
    private int mFragmentPosition = 0;
    private Fragment mFragment;
    private String mPushTypeCode = "";
    private String mSearchCustId = "";
    private String mSearchCtrtId = "";
    private String mSearchMemberId = "";
    //    private WebSocketService mWebSocketService;
    private boolean mIsBound = false;
    private String mCustId = "";
    private String mCtrtId = "";
    private int mCustIdPosition = 0;
    private ArrayList<String> mCustIdMemberList = new ArrayList<String>();
    private ArrayList<String> mCustIdValueList = new ArrayList<String>();
    private ArrayList<String> mCustIdDispList = new ArrayList<String>();
    private int mCtrtIdPosition = 0;
    private ArrayList<String> mCtrtIdValueList = new ArrayList<String>();
    private ArrayList<String> mCtrtIdDispList = new ArrayList<String>();
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<>();
    private boolean isTimeCheck = false;
    private Runnable updateTimeCheck = new Runnable() {
        public void run() {
            try {
                if (isTimeCheck) {
                    long nowTime = mUtil.getRealTime();

                    long loadingTime = mTotalCheckTime - (nowTime - mStartCheckTime);

                    String Hour = String.format("%02d", (loadingTime) / 1000 / 3600);
                    String Min = String.format("%02d", ((loadingTime) / 1000 / 60) % 60);
                    String Sec = String.format("%02d", ((loadingTime) / 1000) % 60);

                    mUtil.getTextView(mActivity, R.id.tvConnectTimeCount).setText(Hour + ":" + Min + ":" + Sec);
                    if (loadingTime >= 0) {
                        updateTimeHandler.postDelayed(this, 1000);
                    } else {
                        isTimeCheck = false;
                        mAppConfig.setIsCustomerConn(false);
                        // 여기서 화면 바꾼다.
                        mUtil.getView(mActivity, R.id.llTop1).setVisibility(View.GONE);
                        mUtil.getView(mActivity, R.id.llTop2).setVisibility(View.VISIBLE);
                        displayView(Constants.MENU_CUSTOMER);

                    }
//                }
                }
            } catch (Exception E) {

            }

        }
    };

    @Override
    protected void onNewIntent(Intent saveIntent) {

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

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

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

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

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

                }
            }
        }
    }

    public void recevicedWebSocket(Intent intentReceived) {

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


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

            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            mActivity.getWindow().setStatusBarTextColor(getResources().getColor(R.color.color_text_01));
//        }
        Dlog.v("mAppConfig.getIntro()=" + mAppConfig.getIntro());

        setIsWebSocket(true);
        setIsMain(true);

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

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

        mAppConfig.setMain(true);
    }

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

        super.onResume();
    }

    @Override
    protected void onPause() {

        super.onPause();

    }

    /**
     * initialize.
     */
    private void setInit() {

        mUtil.getView(mActivity, R.id.llTop1).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llTop2).setVisibility(View.VISIBLE);
        mUtil.getViewUnderline(mActivity, R.id.tvCustId);
        mUtil.getView(mActivity, R.id.rlMainNavi1).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.rlMainNavi2).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.rlMainNavi3).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.rlMainNavi4).setOnClickListener(this);
        displayView(Constants.MENU_CUSTOMER);
        if (mAppConfig.getTemp_Password_Yn().equals("Y")) {
            mCustomDialog.msgAlert(mActivity, Constants.MSG892);
        }

        // 고객관련
        mUtil.getView(mActivity, R.id.btnDelay).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnDisconnect).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnSelectContract).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.rlMainNavi1:
                displayView(Constants.MENU_CUSTOMER);
                break;
            case R.id.rlMainNavi2:
                displayView(Constants.MENU_INSTALL);
                break;
            case R.id.rlMainNavi3:
                displayView(Constants.MENU_THINGS);
                break;
            case R.id.rlMainNavi4:
                displayView(Constants.MENU_ADMIN);
                break;
            case R.id.btnSelectContract: {
                if (mCtrtIdDispList.size() > 0) {
                    // 여기에 선택창 호출
                    Intent intent = new Intent();
                    intent.setClass(mActivity, DialogSpinner.class);
                    intent.putExtra(Constants.EXTRA_SPINNER_LIST1, mCtrtIdDispList);
                    intent.putExtra(Constants.EXTRA_SPINNER_TITLE, mUtil.getString(mActivity, R.string.layout_main_top_05));
                    intent.putExtra(Constants.EXTRA_SPINNER_TYPE, 0);
                    intent.putExtra(Constants.EXTRA_SPINNER_SHOW_TYPE, 1);
                    intent.putExtra(Constants.EXTRA_SPINNER_POSITION, mCtrtIdPosition);
                    mUtil.callActivityForResult(mActivity, intent, Constants.ACT_SPINNER_MAIN, Constants.CHANGE_EVENT_BOTTOM_BOTTOM);
                }
                break;
            }
            case R.id.btnDisconnect: {
                mCustomDialog.msgAlert(mActivity, Constants.MSG701, R.string.MSG_TITLE_000);
                break;
            }
            case R.id.btnDelay: {
                if (mAppConfig.getIsCustomerConn()) {
                    mUtil.getView(mActivity, R.id.btnCustomerConnect).setEnabled(false);
                    mIntent = new Intent(mActivity, CustomerConnection.class);
                    mIntent.putExtra(Constants.EXTRA_CALL_TYPE, "1");
                    mIntent.putExtra(Constants.KEY_CUST_ID, mCustId);
                    mIntent.putExtra(Constants.KEY_CTRT_GRP_ID, mCustId);
                    mIntent.putExtra(Constants.EXTRA_POSITION, mCustIdPosition);
                    mIntent.putExtra(Constants.EXTRA_SPINNER_LIST1, mCustIdDispList);
                    mIntent.putExtra(Constants.EXTRA_SPINNER_LIST2, mCustIdValueList);
                    mIntent.putExtra(Constants.EXTRA_SPINNER_LIST3, mCustIdMemberList);
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_CUSTOMER_CONNECTION1);
                    mUtil.getView(mActivity, btnCustomerConnect).setEnabled(true);

                }
                break;
            }
            default:
                break;
        }
    }


    /**
     * 메뉴 탭 선택.
     *
     * @param view 선택된 메뉴
     */
    private void selectMainNavi(View view) {

        mUtil.getView(mActivity, R.id.rlMainNavi1).setSelected(false);
        mUtil.getView(mActivity, R.id.rlMainNavi2).setSelected(false);
        mUtil.getView(mActivity, R.id.rlMainNavi3).setSelected(false);
        mUtil.getView(mActivity, R.id.rlMainNavi4).setSelected(false);
        view.setSelected(true);
    }

    /**
     * UI display.
     *
     * @param position 보여줄 view index
     */
    private void displayView(int position) {

        switch (position) {
            case Constants.MENU_CUSTOMER:
                LogUtil.i(TAG, "displayView : MENU_CUSTOMER");
                selectMainNavi(mUtil.getView(mActivity, R.id.rlMainNavi1));
                mFragment = new FragmentCustomer();
                break;
            case Constants.MENU_INSTALL:
                selectMainNavi(mUtil.getView(mActivity, R.id.rlMainNavi2));
                mFragment = new FragmentInstall();
                break;
            case Constants.MENU_THINGS:
                selectMainNavi(mUtil.getView(mActivity, R.id.rlMainNavi3));
                mFragment = new FragmentThings();
                break;
            case Constants.MENU_ADMIN:
                selectMainNavi(mUtil.getView(mActivity, R.id.rlMainNavi4));
                mFragment = new FragmentAdmin();
                break;
            default:
                break;
        }
        if (mFragment != null) {
            FragmentManager fmBody = getSupportFragmentManager();
            FragmentTransaction ft = fmBody.beginTransaction();
            if (mFragmentPosition > position) {
                ft.setCustomAnimations(R.anim.left_in, R.anim.right_out);
            } else if (mFragmentPosition < position) {
                ft.setCustomAnimations(R.anim.right_in, R.anim.left_out);
            }
            ft.replace(R.id.frame_container, mFragment);
            ft.commit();
        }
        mFragmentPosition = position;

        if ("Y".equals(mAppConfig.getMasterTransferPopupYn())) {
            // TODO: 2017-05-31 임시비밀번호, 마스터권한양도 팝업 처리방법?
        }
    }

    @Override
    protected void onDestroy() {

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

    }

    @Override
    public void setTitle(CharSequence title) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

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

        try {
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case Constants.ACT_SPINNER_MAIN: {
                        mCtrtIdPosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, -1);
                        mUtil.getButton(mActivity, R.id.btnSelectContract).setText(mCtrtIdDispList.get(mCtrtIdPosition));
                        mCtrtId = mCtrtIdValueList.get(mCtrtIdPosition);
                        mAppConfig.setCustomerCtrtId(mCtrtId);
                        break;
                    }
                    case Constants.ACT_CUSTOMER_CONNECTION1:
                        if (data == null) {
                            return;
                        }
                        mCustIdPosition = data.getIntExtra(Constants.EXTRA_POSITION, 0);
                        resetTime();
                        break;
                    case Constants.ACT_LOGIN:
                        displayView(Constants.MENU_DASHBOARD);
                        break;
                    case Constants.ACT_INVITATION_LIST:
                        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_MEMBER), Constants.HANDLER_DELAY_MILLIS);
                        break;
                    case Constants.ACT_HOME_SELECT_POP:
                        displayView(Constants.MENU_DASHBOARD);
                        break;
                    case Constants.ACT_THINGS_GROUP_ADD:
                        break;
                    case Constants.ACT_THINGS_HOMEHUB_GUIDE:
//                        if (getWebSocketService() != null && !getWebSocketService().isWebSocketConnected()) {
//                            getWebSocketService().webSocketConnect();
//                        }
                        Intent intent = new Intent(mActivity, HomeStart.class);
                        mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_HOME_START);
                        break;
                    case Constants.ACT_HOME_START:
                        mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                        break;
                    case Constants.ACT_MAIN_MORE:
                        displayView(mFragmentPosition);
                        break;
                    default:
                        mFragment = getSupportFragmentManager().findFragmentById(R.id.frame_container);
                        if (mFragment != null) {
                            mFragment.onActivityResult(requestCode, resultCode, data);
                        }
                        break;
                }
            } else {
                switch (requestCode) {
                    case Constants.ACT_HOME_START:
                        displayView(mFragmentPosition);
                        break;
                    case Constants.ACT_MAIN_MORE:
                        if (mAppConfig.getLogout()) {
                            mAppConfig.setLogout(false);
                            return;
                        }
                        displayView(mFragmentPosition);
                        break;
                    default:
                        mFragment = getSupportFragmentManager().findFragmentById(R.id.frame_container);
                        if (mFragment != null) {
                            mFragment.onActivityResult(requestCode, resultCode, data);
                        }
                        break;
                }
                if (mAppConfig.getGoErr()) {
                    setExit();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {

        Dlog.v("onBackPressed()");
        mBackPressCloseHandler.onBackPressed("setExit");
    }

    @Override
    public void onLogout() {

        Dlog.v("onLogout");
//        mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_G_MEMBER_LOGOUT));
        mAppConfig.setAuthToken("");
        mAppConfig.setIsAutoLogin(false);
        SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
        String sql = "";
        sql = mSqlManager.qryUpdateLoginInfoAutoLogin(false);
        db.execSQL(sql);

        mAppConfig.setLogin_Pass("");

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

        mAppConfig.setIsLogin(false);
        mAppConfig.setMain(false);
        Dlog.v(mAppConfig.getIntro());
        mIntent = new Intent(mActivity, Login.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mUtil.callActivityNoAnim(mActivity, mIntent);
        finish();
    }

    @Override
    public void onHomehubStart() {

        Intent intent = new Intent(mActivity, ThingsHomehubGuide.class);
        mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_THINGS_HOMEHUB_GUIDE);
    }

    @Override
    public void onHomeMemberWidthdraw() {

        mCustomDialog.msgAlert(mActivity, Constants.MSG835, R.string.MSG_TITLE_002);
    }

    @Override
    public void setCustomerConnect(String custId, int custIdPosition, ArrayList<String> custIdDispList
            , ArrayList<String> custIdValueList, ArrayList<String> custIdMemberList) {

        mCustId = custId ;
        mCustIdPosition =custIdPosition ;
        mCustIdDispList =custIdDispList ;
        mCustIdValueList =custIdValueList ;
        mCustIdMemberList =custIdMemberList ;
        resetTime();
    }

    void resetTime(){
        Dlog.v("mCustId = " + mCustId);
        Dlog.v("mCustIdPosition = " + mCustIdPosition);
        Dlog.v("mCustIdDispList = " + mCustIdDispList);
        Dlog.v("mCustIdValueList = " + mCustIdValueList);
        Dlog.v("mCustIdMemberList = " + mCustIdMemberList);
        mAppConfig.setIsCustomerConn(true);
        mAppConfig.setCustId(mCustId);
        mAppConfig.setCtrtGroupId(mCustId);
        mAppConfig.setCustomerMemberId(mCustIdMemberList.get(mCustIdPosition));
        mAppConfig.setCustomerPhone(mCustIdValueList.get(mCustIdPosition));
        mUtil.getView(mActivity, R.id.llTop1).setVisibility(View.VISIBLE);
        mUtil.getView(mActivity, R.id.llTop2).setVisibility(View.GONE);
        mUtil.getTextView(mActivity, R.id.tvCustId).setText(mCustId);

        // 여기서 타임오버 설정해야 함
        mStartCheckTime = mUtil.getRealTime();
        Dlog.v("mStartCheckTime = " + mStartCheckTime);
        String Hour = String.format("%02d", (mTotalCheckTime) / 1000 / 3600);
        String Min = String.format("%02d", ((mTotalCheckTime) / 1000 / 60) % 60);
        String Sec = String.format("%02d", ((mTotalCheckTime) / 1000) % 60);
        mUtil.getTextView(mActivity, R.id.tvConnectTimeCount).setText(Hour + ":" + Min + ":" + Sec);
        Dlog.v("mTotalCheckTime = " + Hour + ":" + Min + ":" + Sec);

        isTimeCheck = true;
        updateTimeHandler.postDelayed(updateTimeCheck, 1000);
        mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_CUSTOMER_CTRT), Constants.HANDLER_DELAY_MILLIS);
    }

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

        switch (msgId) {
            case Constants.MSG701:
                if (btnResult == 1) {
                    isTimeCheck = false;
                    mAppConfig.setIsCustomerConn(false);
                    mAppConfig.setCustId("");
                    mAppConfig.setCustomerCtrtId("");
                    // 여기서 화면 바꾼다.
                    mUtil.getView(mActivity, R.id.llTop1).setVisibility(View.GONE);
                    mUtil.getView(mActivity, R.id.llTop2).setVisibility(View.VISIBLE);
                    displayView(Constants.MENU_CUSTOMER);
                }
                break;
            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG805:
                if (btnResult == 1) {
//                    mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_G_MEMBER_LOGOUT));
                    onLogout();
                }
                break;
            case Constants.MSG835:
                if (btnResult == 1) {
                    mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID));
                }
                break;
            case Constants.MSG892:
                mAppConfig.setTemp_Password_Yn("");
                mAppConfig.setLogin_Pass("");
                if (btnResult == 1) {
                    mIntent = new Intent(mActivity, SettingPasswordChange.class);
                    mIntent.putExtra(Constants.EXTRA_PASSWORD, mAppConfig.getLogin_Pass());
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_SETTING_PASSWORD_CHANGE);
                }
                break;
            default:
                break;
        }
    }

    public void sendWsDeviceAlive() {
        HashMap<String, Object> sendParams = new HashMap<>();
        sendParams.put(Constants.KEY_MESSAGE_TYPE, Constants.WEBSOCKET_TYPE_DEVICE_ALIVE);
        sendParams.put(Constants.KEY_DEVICE_ID, mAppConfig.getSelectHomehubDeviceId());
        sendParams.put(Constants.KEY_REQUEST_ID, mAppConfig.getSelectServicehubRequestId());

        getWebSocketService().send(Constants.WEBSOCKET_SEND_DEVICE_ALIVE, sendParams);
    }

    private void resultWsDeviceAlive(JSONObject joResult) throws JSONException {
        String deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
        if (deviceId.equals(mAppConfig.getSelectHomehubDeviceId())) {
            String deviceConn = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_CONN));
            String deviceOnline = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ONLINE));
            String connLastModifiedTime = mUtil.null2string(joResult.get(Constants.KEY_CONN_LAST_MODIFIED_TIME));
            String onlineLastModifiedTime = mUtil.null2string(joResult.get(Constants.KEY_ONLINE_LAST_MODIFIED_TIME));
            String preOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);

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

            String currentOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);

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

    /**
     * 홈허브 장치 상태 정보를 푸쉬받는다(현재 홈그룹에 등록된 홈허브의 상태 정보).
     *
     * @param joResult : json data object
     *
     * @exception JSONException : json parsing exception
     */
    private void notificationWsDeviceContent(JSONObject joResult) throws JSONException {
        JSONObject contentValue = (JSONObject) joResult.get(Constants.KEY_CONTENT_VALUE);
        if (contentValue.has(Constants.KEY_ONLINE)) {
            String deviceId = mUtil.null2string(joResult.get(Constants.KEY_DEVICE_ID));
            String preOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);
            String pushOnlineStatus = mUtil.null2string(((JSONObject) joResult.get(Constants.KEY_CONTENT_VALUE)).getString(Constants
                    .KEY_ONLINE));
            String currentOnlineStatus = "";

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

            currentOnlineStatus = mAppConfig.getSelectCtrtGroupHomehubOnlineState(deviceId);

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

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

        Dlog.v("setExit()");
        mAppConfig.setIntro(false);
        mAppConfig.setGoErr(false);
        mAppConfig.setMain(false);
        getWebSocketService().webSocketDisconnect();
        finish();
    }

    private void sendGetCustomerCtrt() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

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

                    resultGetCustomerCtrt(result);
                }
            });
            httpSend.getMsoCtrt(mCustId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void resultGetCustomerCtrt(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {
                Dlog.v("response.getContent() = " + result.getContent());
                mTotalList.clear();
                mTotalList = mUtil.jsonToArrayListMap(result.getContent());

                if (mTotalList.size() > 0) {
                    mCtrtIdValueList.clear();
                    mCtrtIdDispList.clear();
                    mCtrtIdPosition = 0;
                    mCtrtId = "";
                    for (int row = 0; row < mTotalList.size(); row++) {
                        HashMap<String, Object> tempMap;
                        tempMap = this.mTotalList.get(row);

                        String tempCtrtId = mUtil.null2string(tempMap.get(Constants.KEY_CTRT_ID));
                        mCtrtIdValueList.add(tempCtrtId);
                        mCtrtIdDispList.add(tempCtrtId);
                    }

                    if (mTotalList.size() == 1) {
                        Dlog.v("jino3");
                        mUtil.getView(mActivity, R.id.tvSelectContract).setVisibility(View.VISIBLE);
                        mUtil.getButton(mActivity, R.id.btnSelectContract).setVisibility(View.GONE);
                        mCtrtId = mCtrtIdValueList.get(mCtrtIdPosition);
                        mAppConfig.setCustomerCtrtId(mCtrtId);
                        mUtil.getTextView(mActivity, R.id.tvSelectContract).setText(mCtrtIdDispList.get(mCtrtIdPosition));
                        mUtil.getTextView(mActivity, R.id.tvSelectContract).setSelected(true);
                    } else {
                        mCtrtIdPosition = mTotalList.size()-1;
                        Dlog.v("jino4");
                        mUtil.getView(mActivity, R.id.tvSelectContract).setVisibility(View.GONE);
                        mUtil.getButton(mActivity, R.id.btnSelectContract).setVisibility(View.VISIBLE);

                        mCtrtId = mCtrtIdValueList.get(mCtrtIdPosition);
                        mAppConfig.setCustomerCtrtId(mCtrtId);
                        mUtil.getButton(mActivity, R.id.btnSelectContract).setText(mCtrtIdDispList.get(mCtrtIdPosition));
                        mUtil.getButton(mActivity, R.id.btnSelectContract).setSelected(true);
                        mUtil.getButton(mActivity, R.id.btnSelectContract).setEnabled(true);
                    }
                }
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

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

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                /*case MSG_COM_G_MEMBER_LOGOUT:
                    sendGetMemberLogout();
                    break;*/
                case MSG_COM_G_CUSTOMER_CTRT:
                    sendGetCustomerCtrt();
                    break;
//                case MSG_COM_G_MEMBER:
//                    sendWsMemberAuthAuto();
//                    break;
                case MSG_MAIN_INIT:
                    setInit();
                    break;
//                case MSG_COM_D_HOMEGRP_MEMBERS_MEMBER_ID:
//                    sendDeleteHomegrpMember();
//                    break;
                case MSG_COM_WS_DEVICE_ALIVE:
                    sendWsDeviceAlive();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
