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

package com.ntels.kneet.v3.view;

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.gcm.service.GcmRegister;
import com.ntels.kneet.v3.common.gcm.service.GcmSharedPreferences;
import com.ntels.kneet.v3.common.gcm.service.PushService;
import com.ntels.kneet.v3.common.gcm.support.GcmRegLocalBroadCast;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.mdns.MdnsRegService;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.LogUtil;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;
import com.ntels.kneet.v3.view.dialog.DialogSpinner;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
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.kneet.v3.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 int mType = 0;
    private static final int MSG_COM_G_APP_VERSION = 1;
    private static final int MSG_COM_ACTINIT = 2;
    private static final int MSG_COM_MDNS_INIT = 3;

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

    @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.getLogin()) {
                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.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;
        }
    }

    Handler comHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_APP_VERSION:
                    sendGetAppVersion();
                    break;
                case MSG_COM_ACTINIT:
                    actInit();
                    break;
                case MSG_COM_MDNS_INIT:
                    startMdnsService();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

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

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

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

        LocalBroadcastManager.getInstance(this).registerReceiver(gcmRegLocalBroadCast,
                new IntentFilter(GcmRegLocalBroadCast.INTENT_ACTION));

        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)");
            mServerTitles.add("Kneet3_Custom\n(https://61.40.220.132:5018, 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);
//            setServer(Constants.KEY_URL_KNEET_V3_DEV_CUSTOM);
        }
    }

    /**
     * Notificatoin cancel.
     */
    private void notiCancel() {

        NotificationManager notifier = (NotificationManager) mActivity.getSystemService(
                Context.NOTIFICATION_SERVICE);
        notifier.cancel(Constants.NOTIFICATION_ID);
    }

    /**
     * process start.
     */
    private void start() {

        //gcm 서비스 초기화
        stopPushService();
        startPushService();
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_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);
        }
    }

    /**
     * 푸쉬& GCM 통합 서비스 시작.
     */
    private void startPushService() {

        startService(new Intent(this, PushService.class));
    }

    /**
     * 푸쉬& GCM 통합 서비스 종료.
     */
    private void stopPushService() {

        stopService(new Intent(this, PushService.class));
    }

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

        new MdnsServiceTask().execute();
    }

    private GcmSharedPreferences gcmSharedPreferences;
    private GcmRegLocalBroadCast gcmRegLocalBroadCast = new GcmRegLocalBroadCast() {
        public void onMessage(String msg) {

        }

        public void onMessage(int resultcode, String msg) {

        }

        @Override
        public void onMessage(int action, int resultcode, String msg) {

            super.onMessage(action, resultcode, msg);
            gcmSharedPreferences = new GcmSharedPreferences(mActivity);
            mIsPushSuccess = true;
            switch (action) {
                case GcmRegister.onGCMRegistraterListener.ACTION_SUCESS:
                    // 푸시 키 발급 성공
                    // msg에 키값 반환
                    if (gcmSharedPreferences.isRegistrationID()) {
                        // 등록키 존재 여부 확인
                        Dlog.v("GCM RegID: " + gcmSharedPreferences.getRegistrationID());
                        // GCM 등록키 반환
                        String gcmRegId = gcmSharedPreferences.getRegistrationID();
                        mAppConfig.setPush_Token(gcmRegId);
                    }

                    break;
                // 푸시 사용 불가한 경우
                case GcmRegister.onGCMRegistraterListener.ACTION_NOT_PLAY_SERVICE:
                case GcmRegister.onGCMRegistraterListener.ACTION_DEVICE_NOT_SURPROT:
                case GcmRegister.onGCMRegistraterListener.ACTION_REG_EXCEPTION:
                case GcmRegister.onGCMRegistraterListener.PLAY_SERVICES_RESOLUTION_REQUEST:
                    break;
                case GcmRegister.onGCMRegistraterListener.ACTION_USE_PLAY_SERVICE: // 플레이 서비스
                    // 사용가능
                    break;
                default:
                    break;
            }
        }
    };

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

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

    /**
     * 선택된 서버 정보 셋팅.
     *
     * @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.setsSipUrl(Constants.VSAAS_SIP_URL_KNEET_V3_DEV);
            mAppConfig.setsTurnUrl(Constants.VSAAS_TURN_URL_KEET_V3_DEV);
            mAppConfig.setiTurnPort(Constants.VSAAS_TURN_PORT_KNEET_V3_DEV);
            mAppConfig.setsVsaasDomain(Constants.VSAAS_SIP_DOMAIN_KNEET_V3_DEV);
            mAppConfig.setsSipPassword(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.setsSipUrl(Constants.VSAAS_SIP_URL_KNEET_V3);
            mAppConfig.setsTurnUrl(Constants.VSAAS_TURN_URL_KEET_V3);
            mAppConfig.setiTurnPort(Constants.VSAAS_TURN_PORT_KNEET_V3);
            mAppConfig.setsVsaasDomain(Constants.VSAAS_SIP_DOMAIN_KNEET_V3);
            mAppConfig.setsSipPassword(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_V3_DEV_CUSTOM) {
            mAppConfig.setUrl(Constants.URL_KNEET_V3_DEV_CUSTOM);
            mAppConfig.setSmartUrl(Constants.SMART_URL_KNEET_V3_DEV_CUSTOM);
            mAppConfig.setService_Id(Constants.SERVICE_ID_KNEET_V3_DEV_CUSTOM);
            mAppConfig.setProject_Id(Constants.PROJECT_ID_KNEET_V3_DEV_CUSTOM);
            mAppConfig.setServicehubWebsocketUrl(Constants.URL_SERVICE_HUB_WEBSOCKET_V3_DEV_CUSTOM);
            mAppConfig.setServicehubRestUrl(Constants.URL_SERVICE_HUB_REST_V3_DEV_CUSTOM);
            mAppConfig.setCloudGatewayUrl(Constants.URL_CLOUD_GATEWAY_V3_DEV_CUSTOM);
            mAppConfig.setsSipUrl(Constants.VSAAS_SIP_URL_KNEET_V3_DEV_CUSTOM);
            mAppConfig.setsTurnUrl(Constants.VSAAS_TURN_URL_KEET_V3_DEV_CUSTOM);
            mAppConfig.setiTurnPort(Constants.VSAAS_TURN_PORT_KNEET_V3_DEV_CUSTOM);
            mAppConfig.setsVsaasDomain(Constants.VSAAS_SIP_DOMAIN_KNEET_V3_DEV_CUSTOM);
            mAppConfig.setsSipPassword(Constants.VSAAS_SIP_PASSWORD_KNEET_V3_DEV_CUSTOM);
            mUtil.setPreferences(mActivity, Constants.EXTRA_APPSTART_ID,
                    Constants.APP_START_ID_KNEET_V3_DEV_CUSTOM);
        } 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() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(gcmRegLocalBroadCast);

        Dlog.v("mAppConfig.getIntro()=" + mAppConfig.getIntro());
        mActivity.finish();
    }

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

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

                    resultGetAppVersion(result);
                }
            });
            httpSend.G_app_version(Constants.OS_TYPE, Constants.APP_STORE_CD, mAppConfig.getVer(),
                    mAppConfig.getService_Id());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 서버에 등록된 App 버전 정보 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultGetAppVersion(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.HTTP_result_code));
                if ("00".equals(resultCode)) {
                    setBackLoadLogin();
                } else if ("01".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG819);
                } else if ("99".equals(resultCode)) {
                    // 업데이트 진행해야 함
                    mCustomDialog.msgAlert(mActivity, Constants.MSG821);
                }
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorMsg = mUtil.null2string(joResult.get(Constants.HTTP_err_msg));

                mCustomDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
            }
        } 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, mIntent);
    }

    /**
     * 메인화면으로 이동.
     */
    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,
    }

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

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

    /**
     * 서비스 실행 여부 확인.
     *
     * @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;
    }
}
