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

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

import android.app.Activity;
import android.app.ActivityManager;
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.view.ViewGroup;
import android.widget.ProgressBar;

import com.google.android.gms.analytics.GoogleAnalytics;
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.ntels.kneet.v3.R;
import com.tsengvn.typekit.TypekitContextWrapper;

import java.util.List;
import java.util.TimeZone;
public class CustomActivity extends Activity {

    private AppConfig appConfig;
    private Dialog    dialog;

    private String sActAnim = "";
    private String sActName = "";

    public void setAnimFinish(String sVal) {

        sActAnim = sVal;
    }
    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() ) {
                //                        appConfig.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() ) {
                //                        appConfig.setGoErr(true);
                //                        finish();
                //                    }
                //                }
            }
        }
    };

    public boolean isRunningProcess() {

        boolean isRunning = false;

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

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

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

        return isRunning;
    }

    @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 = appConfig.getTracker(AppConfig.TrackerName.APP_TRACKER);
//        t.setScreenName(sActName);
//        t.send(new HitBuilders.AppViewBuilder().build());
        new Util().callActGoogleAnalytics(sActName);
    }

    @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(mPushMessageReceiver, new IntentFilter(PushMessageLocalBroadCast.INTENT_ACTION));

        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(0, 0);
            }
        }
    }

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

    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 ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                                                                                                              ViewGroup.LayoutParams.WRAP_CONTENT));
        dialog.setCancelable(false);
        dialog.show();
    }

    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 ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                                                                                                              ViewGroup.LayoutParams.WRAP_CONTENT));
        dialog.setCancelable(false);
        dialog.show();
    }

    public void dialog_dismiss() {

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