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

package com.ntels.kneet.v3.common.widget;

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

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.gcm.support.KneetMessageLocalBroadCast;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.RecycleUtils;
import com.ntels.kneet.v3.common.util.Util;
import com.tsengvn.typekit.TypekitContextWrapper;

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.res.Configuration;
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.kneet.v3.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 AppConfig appConfig;
    private Dialog dialog;
    private String sActName = "";
    private String sActAnim = "";

    public void setAnimFinish(String sVal) {

        sActAnim = sVal;
    }

    @Override
    protected void attachBaseContext(Context newBase) {

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        //        String sAnimStart = sActAnim.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)) {

            } 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();
        appConfig.setTimezone_Id(sTZ_ID);

        appConfig.setLanguage_Id(getApplicationContext().getResources().getConfiguration().locale.getLanguage());
        appConfig.setCountry_Id(getApplicationContext().getResources().getConfiguration().locale.getCountry());

        LocalBroadcastManager.getInstance(this).registerReceiver(mKneetMessageReceiver, new IntentFilter(KneetMessageLocalBroadCast.INTENT_ACTION));
    }

    @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 = sActAnim.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) {
            appConfig.loadAppication(savedInstanceState);
            sActAnim = savedInstanceState.getString(Constants.EXTRA_ACT_ANIM);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        outState = appConfig.saveAppication(outState);
        outState.putString(Constants.EXTRA_ACT_ANIM, sActAnim);
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
    }

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

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

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

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

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

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