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

package com.ntels.onecable.common.widget;

import com.google.android.gms.analytics.GoogleAnalytics;

import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.broadcast.KneetMessageLocalBroadCast;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.RecycleUtils;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.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.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
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 :   CustomActionBarActivity
 * 2. FileName  :   CustomActionBarActivity.java
 * 3. Package   :   com.ntels.onecable.common.widget
 * 4. Date      :   2016-12-06
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class CustomActionBarActivity 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 mIsPermissionCheckLogic = false;

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

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

                //                if ( duplicate ) {
                //                    if ( isRunningProcess() ) {
                //                        mAppConfig.setGoErr(true);
                //                        finish();
                //                    }
                //                }
            }
        }
    };

    @Override
    protected void onResume() {

        super.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(mKneetMessageReceiver, new IntentFilter(KneetMessageLocalBroadCast.INTENT_ACTION));
        if (!mIsPermissionCheckLogic) {
            mIsPermission = false;
            checkPermissionInit();
        }
    }

    @Override
    protected void onPause() {

        super.onPause();
    }

    @Override
    protected void onStop() {

        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mKneetMessageReceiver);
        GoogleAnalytics.getInstance(this).reportActivityStop(this);
    }

    @Override
    protected void onStart() {

        super.onStart();
        GoogleAnalytics.getInstance(this).reportActivityStart(this);
    }

    @Override
    public void finish() {

        super.finish();
        dialog_dismiss();
        String sAnimFinish = mActAnim.substring(1);
        if (sAnimFinish.equals("1")) {
            overridePendingTransition(R.anim.abc_slide_out_top, R.anim.abc_slide_out_top);
        } else if (sAnimFinish.equals("2")) {
            overridePendingTransition(R.anim.abc_slide_out_bottom, R.anim.abc_slide_out_bottom);
        } else if (sAnimFinish.equals("3")) {
            overridePendingTransition(R.anim.left_out, R.anim.left_out);
        } else if (sAnimFinish.equals("4")) {
            overridePendingTransition(R.anim.right_out, R.anim.right_out);
        } else {
            if (!Constants.CHANGE_EVENT_CHECK) {
                overridePendingTransition(R.anim.left_in, R.anim.right_out);
            }
        }
    }

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

    @Override
    protected void onDestroy() {

        try {
            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;
        }
    }
    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();
        }
    }

    @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(CustomActionBarActivity.this).sendBroadcast(intent);
                            }
                        }
                    });
                    customDialog.msgAlert(CustomActionBarActivity.this, Constants.MSG923);
                } else {
                    exitPermissionCheckSucess();
                }
                break;
        }

    }

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

}
