/*
 * 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.OnDataSendToReslut;
import com.ntels.onecable.admin.common.gcm.RegistrationIntentService;
import com.ntels.onecable.admin.common.handler.CallWithDelayHandler;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.mdns.MdnsRegService;
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.widget.CustomActivity;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.ntels.onecable.admin.view.dialog.DialogSpinner;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

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

    private static final String TAG = Intro.class.getSimpleName();
    private static final int PUSH_TOKEN_CHECK_INTERVAL = 2000;
    private static final int FINISH_CHECK_INTERVAL = 1000;
    private static final int MSG_COM_P_APP_VERSION = 1;
    private static final int MSG_COM_ACTINIT = 2;
    private static final int MSG_COM_MDNS_INIT = 3;
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    /*통신 관련*/
    private int mType = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private Boolean mIsPushSuccess = false;
    private Boolean mIsMdnsSuccess = false;
    private int mServerPosition = 0;
    private String mPushTypeCode = "";
    private ArrayList<String> mServerTitles = new ArrayList<String>();
    private BroadcastReceiver mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            if (action.equals(Constants.REGISTRATION_READY)) {
                // 액션이 READY일 경우
            } else if (action.equals(Constants.REGISTRATION_GENERATING)) {
                // 액션이 GENERATING일 경우
            } else if (action.equals(Constants.REGISTRATION_COMPLETE)) {
                // 액션이 COMPLETE일 경우
                mIsPushSuccess = true;
                String token = intent.getStringExtra("token");
                mAppConfig.setPush_Token(token);
            }
        }
    };

    @Override
    protected void onNewIntent(Intent saveIntent) {

        super.onNewIntent(saveIntent);
        if (null != saveIntent) {
            Boolean isTemp = saveIntent.getBooleanExtra(KneetMessageLocalBroadCast.INTENT_ACTION_APP_EXIT, false);
            Dlog.v("isTemp", isTemp);
            if (isTemp) {
                setExit();
            }
        }
    }

    @Override
    protected void onDestroy() {

        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onDestroy();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = Intro.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        if (getIntent() != null) {
            mPushTypeCode = mUtil.null2string(getIntent().getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE));
            Dlog.v("jino intro sType = ", mPushTypeCode);
        }

        Dlog.v("mAppConfig.getIntro()=" + mAppConfig.getIntro());
        if (mAppConfig.getIntro()) {
            mIsMdnsSuccess = true;
            if (mAppConfig.getIsLogin()) {
                gotoMainStart();
            } else {
                gotoLoginStart();
            }
        } else {
            View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.intro, null);
            mActivity.setContentView(viewToLoad);
            mAppConfig.Labinit();
            mAppConfig.setIntro(true);
            mAppConfig.setGoErr(false);
            mAppConfig.setMain(false);
            notiCancel();

            float scale = mUtil.getDisplayScale(mActivity);
            mAppConfig.setScale(scale);

            int height = mUtil.str2int(mUtil.getMyDisplayHeight(mActivity));
            int width = mUtil.str2int(mUtil.getMyDisplayWidth(mActivity));

            mAppConfig.setDisplayHeight(height);
            mAppConfig.setDisplayWidth(width);
            int tempHeight = (int) (height * 0.7);
            int tempWidth = (int) ((height * 0.7) * 0.52);
            RelativeLayout.LayoutParams paramView3 = new RelativeLayout.LayoutParams(tempWidth, tempHeight);
            paramView3.addRule(RelativeLayout.CENTER_IN_PARENT);
            mUtil.getView(mActivity, R.id.ivLogo).setLayoutParams(paramView3);
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_ACTINIT), Constants.HANDLER_DELAY_MILLIS);

        }
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
//                case Constants.ACT_LOGIN:
//                    setFinish();
//                    break;
                case Constants.ACT_SPINNER:
                    mServerPosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, 0);
                    setServer(mServerPosition);
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_SPINNER:
                    int connectionType = mUtil.null2int(getIntent().getIntExtra(Constants.EXTRA_CONNECTION_TYPE, Constants
                            .CONNECT_KEY_URL));
                    setServer(connectionType);
                    break;
                default:
                    setFinish();
                    break;
            }
        }
    }

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

        switch (msgId) {
            case Constants.MSG801:
                if (btnResult == 1) {
                    Dlog.v("jino test");
                }
                break;
            case Constants.MSG836:
                if (btnResult == 1) {
                    mAppConfig.setGoErr(true);
                    setResult(RESULT_CANCELED, new Intent());
                    finish();
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                } else {
                    mAppConfig.setGoErr(true);
                    mAppConfig.setIntro(false);
                    setResult(RESULT_CANCELED, new Intent());
                    mActivity.finish();
                }
                break;
            case Constants.MSG821:
                if (btnResult == 1) {
                    // 업데이트 소스(다운로드)
                    Intent marketLaunch = new Intent(Intent.ACTION_VIEW);
                    marketLaunch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    marketLaunch.setData(Uri.parse("market://details?id="
                            + mActivity.getPackageName()));
                    startActivity(marketLaunch);
                    setExit();
                } else {
                    setExit();
                }
                break;
            case Constants.MSG819:
                if (btnResult == 1) {
                    // 업데이트 소스(다운로드)
                    Intent marketLaunch = new Intent(Intent.ACTION_VIEW);
                    marketLaunch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    marketLaunch.setData(Uri.parse("market://details?id="
                            + mActivity.getPackageName()));
                    startActivity(marketLaunch);
                    setExit();
                } else {
                    setBackLoadLogin();
                }
                break;
            default:
                break;
        }
    }

    /**
     * initialize.
     */
    private void actInit() {
        // 강제 종료시 복구를 위한 코드
        getUUid();
        // 버전확인
        appVerCheck();

        //mdns 서비스 초기화
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_MDNS_INIT), Constants.HANDLER_DELAY_MILLIS);

        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Constants
                .REGISTRATION_READY));
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Constants
                .REGISTRATION_GENERATING));
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Constants
                .REGISTRATION_COMPLETE));


        if (mAppConfig.isDebuggable(mActivity)) {
            mServerTitles.clear();
            mServerTitles.add("Kneet3_개발\n(https://dev.allofthings.com:5018, 30001)");
            mServerTitles.add("Kneet3_운영\n(http://52.163.90.87:5017, 30001)");

            Intent intent = new Intent();
            intent.setClass(mActivity, DialogSpinner.class);
            intent.putExtra(Constants.EXTRA_SPINNER_LIST1, mServerTitles);
            intent.putExtra(Constants.EXTRA_SPINNER_TITLE, "접속 서버 선택");
            intent.putExtra(Constants.EXTRA_SPINNER_TYPE, 0);
            intent.putExtra(Constants.EXTRA_SPINNER_POSITION, mServerPosition);
            mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_SPINNER);
        } else {
            setServer(Constants.KEY_URL_KNEET_V3);
        }
    }

    /**
     * Instance ID를 이용하여 디바이스 토큰을 가져오는 RegistrationIntentService를 실행한다.
     */
    public void getInstanceIdToken() {

        if (checkPlayServices()) {
            // Start IntentService to register this application with GCM.
            Intent intent = new Intent(this, RegistrationIntentService.class);
            startService(intent);
        }
    }

    /**
     * Google Play Service를 사용할 수 있는 환경이지를 체크한다. 아이스크림 샌드위치 이상 중국의 경우 또는 구글 서비스를 사용하지 못하는 경우는 다른 방안을 사용해야
     */
    private boolean checkPlayServices() {

//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//            GoogleApiAvailability api = GoogleApiAvailability.getInstance();
//            int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
//            if (code != ConnectionResult.SUCCESS) {
//                api.getErrorDialog(this, code, 0).show();
//                return false;
//            }
//        }
        return true;
    }

    /**
     * Notificatoin cancel.
     */
    private void notiCancel() {
        NotificationManager notifier = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
        notifier.cancel(Constants.NOTIFICATION_ID);
    }

    /**
     * process start.
     */
    private void start() {
        dialog_show1();
        //gcm 서비스 초기화
        getInstanceIdToken();

        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_APP_VERSION), Constants.HANDLER_DELAY_MILLIS);
    }

    /**
     * App 버전 가져오기.
     */
    private void appVerCheck() {
        // 어플 버전 정보 체크
        PackageManager pm = this.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
            String versionName = pi.versionName;
            mAppConfig.setVer(versionName);
        } catch (PackageManager.NameNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * UUID 가져오기.
     */
    private void getUUid() {
        // IMEI, IMSI
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String imei = telephonyManager.getDeviceId();
        String imsi = telephonyManager.getSubscriberId();

        // MAC ADDRESS
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String macAddress = wifiInfo.getMacAddress();

        if (mUtil.null2string(imei).equals("")) {
            if (mUtil.null2string(macAddress).equals("")) {
                mCustomDialog.msgAlert(mActivity, Constants.MSG836);
            } else {
                mAppConfig.setUuid(macAddress);
            }
        } else {
            mAppConfig.setUuid(imei);
        }
    }

    /**
     * startMdnsService.
     */
    private void startMdnsService() {

        new MdnsServiceTask().execute();
    }

    /**
     * Handler 메세지 전송.
     */
    public void setBackLoadLogin() {

//        handler.sendEmptyMessageDelayed(0, PUSH_TOKEN_CHECK_INTERVAL); // ms,

        new CallWithDelayHandler(this).callWithDelayField("mIsPushSuccess", "gotoLoginStart", PUSH_TOKEN_CHECK_INTERVAL);
    }

//
//    private Handler handler = new Handler(new Handler.Callback() {
//        @Override
//        public boolean handleMessage(Message message) {
//
//            if (!mIsPushSuccess) {
//                Dlog.v("handler : " + mAppConfig.getPush_Token());
//                setBackLoadLogin();
//            } else {
//                gotoLoginStart();
//            }
//            return false;
//        }
//    });


    /**
     * 선택된 서버 정보 셋팅.
     *
     * @param val 선택된 서버 index
     */
    private void setServer(int val) {

        if (val == Constants.KEY_URL_KNEET_V3_DEV) {
            mAppConfig.setUrl(Constants.URL_KNEET_V3_DEV);
            mAppConfig.setSmartUrl(Constants.SMART_URL_KNEET_V3_DEV);
            mAppConfig.setService_Id(Constants.SERVICE_ID_KNEET_V3_DEV);
            mAppConfig.setProject_Id(Constants.PROJECT_ID_KNEET_V3_DEV);
            mAppConfig.setServicehubWebsocketUrl(Constants.URL_SERVICE_HUB_WEBSOCKET_V3_DEV);
            mAppConfig.setServicehubRestUrl(Constants.URL_SERVICE_HUB_REST_V3_DEV);
            mAppConfig.setCloudGatewayUrl(Constants.URL_CLOUD_GATEWAY_V3_DEV);
            mAppConfig.setSipUrl(Constants.VSAAS_SIP_URL_KNEET_V3_DEV);
            mAppConfig.setTurnUrl(Constants.VSAAS_TURN_URL_KEET_V3_DEV);
            mAppConfig.setTurnPort(Constants.VSAAS_TURN_PORT_KNEET_V3_DEV);
            mAppConfig.setVsaasDomain(Constants.VSAAS_SIP_DOMAIN_KNEET_V3_DEV);
            mAppConfig.setSipPassword(Constants.VSAAS_SIP_PASSWORD_KNEET_V3_DEV);
            mUtil.setPreferences(mActivity, Constants.EXTRA_APPSTART_ID, Constants.APP_START_ID_KNEET_V3_DEV);
        } else if (val == Constants.KEY_URL_KNEET_V3) {
            mAppConfig.setUrl(Constants.URL_KNEET_V3);
            mAppConfig.setSmartUrl(Constants.SMART_URL_KNEET_V3);
            mAppConfig.setService_Id(Constants.SERVICE_ID_KNEET_V3);
            mAppConfig.setProject_Id(Constants.PROJECT_ID_KNEET_V3);
            mAppConfig.setServicehubWebsocketUrl(Constants.URL_SERVICE_HUB_WEBSOCKET_V3);
            mAppConfig.setServicehubRestUrl(Constants.URL_SERVICE_HUB_REST_V3);
            mAppConfig.setCloudGatewayUrl(Constants.URL_CLOUD_GATEWAY_V3);
            mAppConfig.setSipUrl(Constants.VSAAS_SIP_URL_KNEET_V3);
            mAppConfig.setTurnUrl(Constants.VSAAS_TURN_URL_KEET_V3);
            mAppConfig.setTurnPort(Constants.VSAAS_TURN_PORT_KNEET_V3);
            mAppConfig.setVsaasDomain(Constants.VSAAS_SIP_DOMAIN_KNEET_V3);
            mAppConfig.setSipPassword(Constants.VSAAS_SIP_PASSWORD_KNEET_V3);
            mUtil.setPreferences(mActivity, Constants.EXTRA_APPSTART_ID, Constants.APP_START_ID_KNEET_V3);
        } else if (val == Constants.KEY_URL_KNEET_V2_DEV_CUSTOM) {
            mAppConfig.setUrl(Constants.URL_KNEET_V2_DEV_CUSTOM);
            mAppConfig.setSmartUrl(Constants.SMART_URL_KNEET_V2_DEV_CUSTOM);
            mAppConfig.setService_Id(Constants.SERVICE_ID_KNEET_V2_DEV_CUSTOM);
            mAppConfig.setProject_Id(Constants.PROJECT_ID_KNEET_V2_DEV_CUSTOM);
            mUtil.setPreferences(mActivity, Constants.EXTRA_APPSTART_ID, Constants.APP_START_ID_KNEET_V2_CUSTOM);
        }
        start();
    }

    /**
     * Activity 종료 처리.
     */
    private void setFinish() {
        Dlog.v("mAppConfig.getIntro()=" + mAppConfig.getIntro());
        mActivity.finish();
    }

    /**
     * 서버에 등록된 App 버전 정보 요청.
     */
    private void sendPostAppVersion() {

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

                    resultPostAppVersion(result);
                }
            });
            httpSend.P_app_version(Constants.OS_TYPE, mAppConfig.getVer());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 서버에 등록된 App 버전 정보 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostAppVersion(Response result) {

        try {
            if (result.getStatusCode() == Response.OK) {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                if ("00".equals(resultCode)) {
                    setBackLoadLogin();
                } else if ("01".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG819);
                } else if ("99".equals(resultCode)) {
                    // 업데이트 진행해야 함
                    // TODO: 2017-05-31 테스트 후 아래 주석 풀어야함
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG821);
                    setBackLoadLogin();
                }
            } 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));

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

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

        mAppConfig.setIntro(false);
        Dlog.v(mAppConfig.getIntro());
        finish();
    }

    /**
     * 로그인 activity로 이동.
     */
    private void gotoLoginStart() {

        Intent intent = new Intent(mActivity, Login.class);
        Dlog.v("jino intro1 sType = ", mPushTypeCode);
        if (!"".equals(mPushTypeCode)) {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, mPushTypeCode);
        } else {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, "");
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_LOGIN);
        mUtil.callActivityNoAnim(mActivity, intent);
        setFinishLoading();
    }

    /**
     * 메인화면으로 이동.
     */
    private void gotoMainStart() {

        Intent intent = new Intent(mActivity, Main.class);
        Dlog.v("jino intro2 sType = ", mPushTypeCode);
        if (!"".equals(mPushTypeCode)) {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, mPushTypeCode);
        } else {
            intent.putExtra(Constants.EXTRA_PUSH_TYPE_CODE, "");
        }

        if ("HOME_MEM_INV".equals(mPushTypeCode)) {
            //    홈 초대 받음
        } else if ("HOME_MEM_REF".equals(mPushTypeCode)) {
            //    초대했는데 거절 당할 시
        } else if ("HOME_MEM_BAN".equals(mPushTypeCode)) {
            //    홈 강퇴 받음
            LogUtil.i(TAG, "gotoMainStart : HOME_MEM_BAN!!");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ("HOME_MEM_SEL".equals(mPushTypeCode)) {
            //    홈 자진 탈퇴 받음
        } else if ("HOME_DEL".equals(mPushTypeCode)) {
            //    홈 삭제
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ("DVC_CER_REV".equals(mPushTypeCode)) {
            //    단말 인증 해지 됨
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } 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)) {
            //    홈 허브가 삭제됨
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ("DVC_OWN_CHG".equals(mPushTypeCode)) {
            //    장치 소유주 변경 알림
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ("MEM_ALL_OUT".equals(mPushTypeCode)) {
            //    멤버 All out 시
        } else if ("MEM_ANY_IN".equals(mPushTypeCode)) {
            //    멤버 Any in 시
        } else if ("HOME_LOC_CHG".equals(mPushTypeCode)) {
            //    홈 위치 변경 알림
        } else if ("MEM_DVC_DEL".equals(mPushTypeCode)) {
            //    단말 등록 해지 알림
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ("HOME_RELOAD".equals(mPushTypeCode)) {
            //    홈 멤버 정보 재조회 알림
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        } else if ("LOGOUT".equals(mPushTypeCode)) {
            //    강제 로그아웃 시킴
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }

        mUtil.callActivityNoAnim(mActivity, intent);
        setFinishLoading();
    }

    /**
     * 로딩 완료.
     */
    public void setFinishLoading() {

//        finishhandler.sendEmptyMessageDelayed(0, FINISH_CHECK_INTERVAL); // ms,
        new CallWithDelayHandler(this).callWithDelayMethod("isFinish", true, "setFinish", FINISH_CHECK_INTERVAL);
    }

    private Boolean isFinish() {
        if (!mIsMdnsSuccess) {
            Dlog.v("handler : " + mAppConfig.getPush_Token());
            return false;
//        } else if (!mAppConfig.getMain()) {
//            return false;
        } else {
            return true;
        }

    }
//
//    private Handler finishhandler = new Handler(new Handler.Callback() {
//        @Override
//        public boolean handleMessage(Message message) {
//
//            if (!mIsMdnsSuccess) {
//                Dlog.v("handler : " + mAppConfig.getPush_Token());
//                setFinishLoading();
//            } else if (!mAppConfig.getMain()) {
//                setFinishLoading();
//            } else {
//                setFinish();
//            }
//            return false;
//        }
//    });

    /**
     * 서비스 실행 여부 확인.
     *
     * @param serviceClassName 확인할 서비스 클래스 이름
     *
     * @return 실행 여부
     */
    public boolean isServiceRunning(String serviceClassName) {

        final ActivityManager activityManager = (ActivityManager) mActivity.getSystemService(
                Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RunningServiceInfo> services =
                activityManager.getRunningServices(Integer.MAX_VALUE);

        for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serviceClassName)) {
                return true;
            }
        }
        return false;
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_APP_VERSION:
                    dialog_show();
                    sendPostAppVersion();
                    break;
                case MSG_COM_ACTINIT:
//                    dialog_show();
                    if (getIsPermission()) {
                        actInit();
                    } else {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(mType), Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                case MSG_COM_MDNS_INIT:
                    startMdnsService();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * MDNS 등록 서비스 task.
     */
    private class MdnsServiceTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
                if (isServiceRunning(MdnsRegService.class.getName())) {
                    stopService(new Intent(mActivity, MdnsRegService.class));
                } else {
                    startService(new Intent(mActivity, MdnsRegService.class));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
            mIsMdnsSuccess = true;
        }
    }
}
