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

package com.ntels.onecable.admin.common.widget;


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.util.Dlog;
import com.ntels.onecable.admin.common.util.RecycleUtils;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.tsengvn.typekit.TypekitContextWrapper;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup.LayoutParams;
import android.widget.ProgressBar;

import java.util.List;
import java.util.TimeZone;

/**
 * <pre>
 * 1. ClassName :   CustomActivity
 * 2. FileName  :   CustomActivity.java
 * 3. Package   :   com.ntels.onecable.admin.common.widget
 * 4. Date      :   2016-12-06
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class CustomActivity extends AppCompatActivity {

    protected static final int BACK_PRESS_VALID_TIME = 2000;
    private final int MY_PERMISSION_REQUEST_STORAGE = 100;

    private AppConfig mAppConfig;
    private Dialog mDialog;
    private String mActName = "";
    private String mActAnim = "";
    private Boolean mIsPermission = false;
    private Boolean mIsWebSocket = false;
    private Boolean mIsPermissionCheckLogic = false;
    private WebSocketService mWebSocketService;
    private Boolean mIsMain = false;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Dlog.i("onServiceConnected!!");
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            mWebSocketService = binder.getService();
            // 웹소켓이 연결되기전 Resume가 진행되면 connect 를 다시 구동한다
            if (mIsWebSocket) {
                if (mWebSocketService != null) {
                    if (!mWebSocketService.isWebSocketConnected()) {
                        mWebSocketService.webSocketConnect();
                    }
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
//            mIsBound = false;
            Dlog.i("onServiceDisconnected!!");
            mWebSocketService = null;
            Dlog.i("onServiceDisconnected11!!");
        }
    };
    private KneetMessageLocalBroadCast mKneetMessageReceiver = new KneetMessageLocalBroadCast() {
//        @Override
//        public void onMessage(String messageType, String msg, Boolean bVal) {
//
//            super.onMessage(messageType, msg, bVal);
//            Dlog.v(mKneetMessageReceiver);
//            if (KneetMessageLocalBroadCast.INTENT_DUPLICATE_LOGIN.equals(messageType)) {
//                //                if ( duplicate ) {
//                //                    if ( isRunningProcess() ) {
//                //                        mAppConfig.setGoErr(true);
//                //                        finish();
//                //                    }
//                //                }
//            } else if (KneetMessageLocalBroadCast.INTENT_ACTION_APP_EXIT.equals(messageType)) {
//                Intent intent = getIntent();
//                intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_APP_EXIT, bVal);
//                onNewIntent(intent);
//                Dlog.v(intent);
//            } else if (KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE.equals(messageType)) {
//                Dlog.v(bVal);
//                Intent intent = getIntent();
//                intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE, bVal);
//                onNewIntent(intent);
//                Dlog.v(intent);
//            } else if (KneetMessageLocalBroadCast.INTENT_ACTION_WEBSOCKET_MSG_RECEIVED.equals(messageType)) {
//                Dlog.v(bVal);
//                Intent intent = getIntent();
//                intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_WEBSOCKET_MSG_RECEIVED, bVal);
//                onNewIntent(intent);
//                Dlog.v(intent);
//
//                //                if ( duplicate ) {
//                //                    if ( isRunningProcess() ) {
//                //                        mAppConfig.setGoErr(true);
//                //                        finish();
//                //                    }
//                //                }
//            }
//        }

        @Override
        public void onMessage(String messageType, Intent intentData) {
            super.onMessage(messageType, intentData);
            Dlog.v(intentData);

            String nameType = intentData.getStringExtra(INTENT_NAME_TYPE);

            if (nameType.equals(KneetMessageLocalBroadCast.INTENT_ACTION_HOMEHUB_STATE_CHANGE)) {
                setHomeHubStateAll();
            } else if (nameType.equals(KneetMessageLocalBroadCast.INTENT_ACTION_WEBSOCKET_MSG_RECEIVED)) {
                recevicedWebSocket(intentData);
            }

//            Dlog.v("mKneetMessageReceiver mIsMain = " + mIsMain);
//            if (mIsMain) {
            Bundle bundle = intentData.getExtras();

            Intent intent = getIntent();
            intent.putExtra(Constants.EXTRA_BUNDLE_DATA, bundle);
            onNewIntent(intent);
//            }
        }
    };

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 타이틀과 리스트를 보여준다.
     */
    public void setHomeHubStateAll() {

    }

    public void recevicedWebSocket(Intent intentReceived) {

    }

    public WebSocketService getWebSocketService() {
        return mWebSocketService;
    }

    public void setWebSocketService(WebSocketService webSocketService) {
        mWebSocketService = webSocketService;
    }

    public void setAnimFinish(String sVal) {

        mActAnim = sVal;
    }

    @Override
    protected void attachBaseContext(Context newBase) {

        super.attachBaseContext(TypekitContextWrapper.wrap(newBase));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mAppConfig = (AppConfig) getApplicationContext();
        if (savedInstanceState != null) {
            mAppConfig.loadAppication(savedInstanceState);
            mActName = savedInstanceState.getString(Constants.EXTRA_ACT_NAME);
            mActAnim = savedInstanceState.getString(Constants.EXTRA_ACT_ANIM);
        } else {
            Intent intent = getIntent();
            mActName = intent.getStringExtra(Constants.EXTRA_ACT_NAME);
            mActAnim = intent.getStringExtra(Constants.EXTRA_ACT_ANIM);
        }
        if (mActAnim == null) {
            mActAnim = "00";
        }
//        Tracker t = mAppConfig.getTracker(AppConfig.TrackerName.APP_TRACKER);
//        t.setScreenName(mActName);
//        t.send(new HitBuilders.AppViewBuilder().build());
        new Util().callActGoogleAnalytics(mActName);

        //        String sAnimStart = mActAnim.substring(0, 1);
        //        if ( sAnimStart.equals("1") ) {
        //            overridePendingTransition(R.anim.abc_slide_in_top, R.anim.abc_slide_in_top);
        //        } else if ( sAnimStart.equals("2") ) {
        //            overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_in_bottom);
        //        } else if ( sAnimStart.equals("3") ) {
        //            overridePendingTransition(R.anim.left_in, R.anim.left_in);
        //        } else if ( sAnimStart.equals("4") ) {
        //            overridePendingTransition(R.anim.right_in, R.anim.right_in);
        //        } else {
        //            if ( !Constants.CHANGE_EVENT_CHECK ) {
        //                overridePendingTransition(R.anim.right_in, R.anim.left_out);
        //            }
        //        }
        LocalBroadcastManager.getInstance(this).registerReceiver(mKneetMessageReceiver, new IntentFilter(KneetMessageLocalBroadCast
                .INTENT_ACTION));
    }

    @Override
    protected void onStart() {
        super.onStart();
        Dlog.v("onStart mIsMain = " + mIsMain);
//        GoogleAnalytics.getInstance(this).reportActivityStart(this);
        if (mIsWebSocket) {
//            if (mWebSocketService == null) {
            Intent intent = new Intent(this, WebSocketService.class);
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
//            }
        }
    }

    @Override
    protected void onResume() {

        super.onResume();
        Dlog.v("onResume");
        TimeZone tz = TimeZone.getDefault();
        String sTZ_ID = tz.getID();
        mAppConfig.setTimezone_Id(sTZ_ID);

        mAppConfig.setLanguage_Id(getApplicationContext().getResources().getConfiguration().locale.getLanguage());
        mAppConfig.setCountry_Id(getApplicationContext().getResources().getConfiguration().locale.getCountry());
        //		LocalBroadcastManager.getInstance(this).registerReceiver(mPushMessageReceiver, new IntentFilter(PushMessageLocalBroadCast
        // .INTENT_ACTION));

        if (!mIsPermissionCheckLogic) {
            mIsPermission = false;
            checkPermissionInit();
        }

        Dlog.v("isAppIsInBackground = " + isAppIsInBackground());

        if (mIsWebSocket) {
            if (mWebSocketService != null) {
                if (!mWebSocketService.isWebSocketConnected()) {
                    mWebSocketService.webSocketConnect();
                }
            }
        }
    }

    @Override
    protected void onPause() {

        super.onPause();
        Dlog.v("onPause");
        Dlog.v("isAppIsInBackground = " + isAppIsInBackground());
        if (mIsWebSocket) {
            if (mWebSocketService != null) {
                if (mWebSocketService.isWebSocketConnected()) {
                    Dlog.v("isAppIsInBackground = " + isAppIsInBackground());
                    if (isAppIsInBackground()) {
                        Dlog.v("isAppIsInBackground = " + isAppIsInBackground());
                        mWebSocketService.webSocketDisconnect();
                        Dlog.v("isAppIsInBackground = " + isAppIsInBackground());
                    }
                }
            }
        }
    }

    @Override
    protected void onStop() {
        Dlog.v("onStop mIsMain = " + mIsMain);
//        if (!mIsMain) {
        if (mIsWebSocket) {
//                if (mWebSocketService != null) {
            Dlog.v("onStop unbindService");
            unbindService(mServiceConnection);
//                }
        }
//        }
//        GoogleAnalytics.getInstance(this).reportActivityStop(this);
        super.onStop();
    }

    @Override
    public void finish() {

        super.finish();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mKneetMessageReceiver);
        dialog_dismiss();
        String sAnimFinish = mActAnim.substring(1);
        if (sAnimFinish.equals("1")) {
            overridePendingTransition(R.anim.abc_slide_in_top, R.anim.abc_slide_out_top);
        } else if (sAnimFinish.equals("2")) {
            overridePendingTransition(R.anim.bottom_up, R.anim.bottom_down);
        } else if (sAnimFinish.equals("3")) {
            overridePendingTransition(R.anim.right_in, R.anim.left_out);
        } else if (sAnimFinish.equals("4")) {
            overridePendingTransition(R.anim.left_in, R.anim.right_out);
        } else {
            if (!Constants.CHANGE_EVENT_CHECK) {
                overridePendingTransition(0, 0);
            }
        }
    }

    @Override
    protected void onDestroy() {

        try {
//            if (mIsMain) {
//                if (mIsWebSocket) {
//                    if (mWebSocketService != null) {
//                        Dlog.v("onStop unbindService");
//                        unbindService(mServiceConnection);
//                    }
//                }
//                LocalBroadcastManager.getInstance(this).unregisterReceiver(mKneetMessageReceiver);
//            }
            RecycleUtils recycleUtils = new RecycleUtils();
            recycleUtils.recursiveRecycle(getWindow().getDecorView());
            // 메모리 클리어를 위해 액티비티 종료
            System.gc();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mAppConfig.loadAppication(savedInstanceState);
            mActAnim = savedInstanceState.getString(Constants.EXTRA_ACT_ANIM);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        outState = mAppConfig.saveAppication(outState);
        outState.putString(Constants.EXTRA_ACT_ANIM, mActAnim);
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
    }

    /**
     * Dialog display.
     */
    public void dialog_show() {

        if (mDialog != null) {
            //            mDialog.cancel();
            //            mDialog = null;
            return;
        }
        mDialog = new Dialog(this, R.style.NTLES_Dialog1);
        mDialog.addContentView(new ProgressBar(this, null, android.R.attr.progressBarStyleInverse), new LayoutParams(LayoutParams
                .WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        mDialog.setCancelable(false);
        mDialog.show();
    }

    /**
     * Dialog display.
     */
    public void dialog_show1() {

        if (mDialog != null) {
            //            mDialog.cancel();
            //            mDialog = null;
            return;
        }
        mDialog = new Dialog(this, R.style.NTLES_Dialog2);
        mDialog.addContentView(new ProgressBar(this, null, android.R.attr.progressBarStyleInverse), new LayoutParams(LayoutParams
                .WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        mDialog.setCancelable(false);
        mDialog.show();
    }

    /**
     * Dialog dismiss.
     */
    public void dialog_dismiss() {

        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    public Boolean getIsPermission() {
        return mIsPermission;
    }

    private void checkPermissionInit() {
        mIsPermissionCheckLogic = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkPermission();
        } else {
            exitPermissionCheckSucess();
        }
    }

    /**
     * Permission check.
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void checkPermission() {

//  <uses-permission android:name="android.permission.BLUETOOTH"/>
//  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
//  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
//  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
//  <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
//  <uses-permission android:name="android.permission.CAMERA"/>
//  <uses-permission android:name="android.permission.FLASHLIGHT"/>
//  <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
//  <uses-permission android:name="android.permission.GET_TASKS"/>
//  <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
//  <uses-permission android:name="android.permission.INTERNET"/>
//  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
//  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
//  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
//  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
//  <uses-permission android:name="android.permission.VIBRATE"/>
//  <uses-permission android:name="android.permission.WAKE_LOCK"/>
//  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
//  <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
//
//  <!-- 20160816 IP Camera 추가로 인해 권한 추가 -->
//  <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
//  <uses-permission android:name="android.permission.RECORD_AUDIO"/>
//  <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
//  <uses-permission android:name="android.permission.PHONE_CALLS"/>
//  <uses-permission android:name="android.permission.MICROPHONE"/>
//  <uses-permission android:name="android.permission.AUDIO_SETTINGS"/>
        if (checkSelfPermission(Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.CHANGE_WIFI_MULTICAST_STATE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.FLASHLIGHT) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.GET_TASKS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.RECEIVE_BOOT_COMPLETED) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.CHANGE_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.PHONE_CALLS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.MICROPHONE) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
                ) {
            requestPermissions(new String[]{
                    Manifest.permission.BLUETOOTH
                    , Manifest.permission.ACCESS_NETWORK_STATE
                    , Manifest.permission.ACCESS_WIFI_STATE
                    , Manifest.permission.CHANGE_WIFI_STATE
                    , Manifest.permission.CHANGE_WIFI_MULTICAST_STATE
                    , Manifest.permission.CAMERA
                    , Manifest.permission.GET_ACCOUNTS
                    , Manifest.permission.INTERNET
                    , Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.READ_PHONE_STATE
                    , Manifest.permission.RECEIVE_BOOT_COMPLETED
                    , Manifest.permission.VIBRATE
                    , Manifest.permission.WAKE_LOCK
                    , Manifest.permission.CHANGE_NETWORK_STATE
                    , Manifest.permission.RECORD_AUDIO
                    , Manifest.permission.MODIFY_AUDIO_SETTINGS
            }, MY_PERMISSION_REQUEST_STORAGE);
        } else {
            exitPermissionCheckSucess();
        }
    }

    public Boolean getIsWebSocket() {
        return mIsWebSocket;
    }

    public void setIsWebSocket(Boolean webSocket) {
        mIsWebSocket = webSocket;
    }

    public Boolean getIsMain() {
        return mIsMain;
    }

    public void setIsMain(Boolean isMain) {
        mIsMain = isMain;
    }

    @Override
    @TargetApi(Build.VERSION_CODES.M)
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSION_REQUEST_STORAGE:
                // 권한 거부
                // 사용자가 해당권한을 거부했을때 해주어야 할 동작을 수행합니다
                if (checkSelfPermission(Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.CHANGE_WIFI_MULTICAST_STATE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.FLASHLIGHT) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.GET_TASKS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.RECEIVE_BOOT_COMPLETED) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.CHANGE_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                        || checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.PHONE_CALLS) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.MICROPHONE) != PackageManager.PERMISSION_GRANTED
//                || checkSelfPermission(Manifest.permission.AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
                        ) {
                    CustomDialog customDialog = new CustomDialog();
                    customDialog.setOnMsgAlterToResultEvent(new CustomDialog.OnMsgAlterToResult() {
                        @Override
                        public void resultCustomDialogResponse(int msgId, int btnResult) {
                            if (btnResult == 1) {
                                checkPermission();
                            } else {
                                Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
                                intent.putExtra(KneetMessageLocalBroadCast.INTENT_NAME_TYPE, KneetMessageLocalBroadCast
                                        .INTENT_ACTION_APP_EXIT);
                                intent.putExtra(KneetMessageLocalBroadCast.INTENT_ACTION_APP_EXIT, true);
                                LocalBroadcastManager.getInstance(CustomActivity.this).sendBroadcast(intent);
                            }
                        }
                    });
                    customDialog.msgAlert(CustomActivity.this, Constants.MSG923);
                } else {
                    exitPermissionCheckSucess();
                }

                break;
        }

    }

    void exitPermissionCheckSucess() {
        mIsPermission = true;
        mIsPermissionCheckLogic = false;
    }

    public Boolean getWebSocketState() {
        Boolean isWebSocketState = false;
        if (getWebSocketService() != null) {
            if (getWebSocketService().isWebSocketConnected()) {
                isWebSocketState = true;
            }
        }
        return isWebSocketState;
    }

    /**
     * Process가 실행중인지 여부 확인.
     */
    public boolean isRunningProcess() {

        boolean isRunning = false;

        ActivityManager actMng = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningAppProcessInfo> list = actMng.getRunningAppProcesses();

        for (RunningAppProcessInfo rap : list) {
            if (rap.processName.equals(getPackageName())) {
                if (rap.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
                    setResult(RESULT_CANCELED);
                isRunning = true;
                break;
            }
        }

        return isRunning;
    }


    /**
     * App이 백그라운드에서 실행중인지 확인.
     *
     * @return 백그라운드 실행여부
     */
    private boolean isAppIsInBackground() {

        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }
}

