package com.sheep.gamegroup.absBase;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.sheep.gamegroup.util.ActionUtil;
import com.sheep.gamegroup.view.dialog.DialogLoading;
import com.sheep.jiuyan.samllsheep.R;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by kemllor on 2017/12/15.
 */

public abstract class BaseActivity extends RxAppCompatActivity {

    protected DialogLoading dialogLoading;
    public Unbinder unbinder;

    protected boolean needRegisterEventBus() {
        return false;
    }

    protected boolean needButterKnife() {
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setCustomView(R.layout.title);
            actionBar.hide();
            actionBar.setDisplayShowCustomEnabled(true);
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setElevation(0);
            Toolbar toolbar = (Toolbar) actionBar.getCustomView().getParent();
            toolbar.setContentInsetsRelative(0, 0);
        }
        setContentView(getLayoutId());
        if (needButterKnife())
            unbinder = ButterKnife.bind(this);
        if (needRegisterEventBus())
            EventBus.getDefault().register(this);
        initView();
        initListener();
        initData();
    }

    public boolean isShowing() {
        return dialogLoading != null && dialogLoading.getAlertDialog() != null && dialogLoading.getAlertDialog().isShowing();
    }

    public void showProgress() {
        hideProgress();
        dialogLoading = DialogLoading.showDialog(this);
    }

    protected void showProgress(boolean cancel) {
        hideProgress();
        dialogLoading = DialogLoading.showDialog(this, cancel);
    }


    public void hideProgress() {
        if (isShowing()) {
            try {
                dialogLoading.getAlertDialog().dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkNextAction(this.getClass().getSimpleName());
    }

    protected boolean checkNextAction(String key) {
        final Object action = ActionUtil.getInstance().getAction(key);
        if (action != null) {
            //延时一会儿，不然有可能操作会无效
            Observable.just(1).delay(50L, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new AbsObserver<Integer>() {
                        @Override
                        public void onNext(Integer integer) {
                            doNextAction(action);
                        }
                    });
            return true;
        }
        return false;
    }

    public void doNextAction(Object action) {

    }

    protected abstract int getLayoutId();

    public abstract void initView();

    public void initListener() {

    }

    public void initData() {

    }

    @Override
    protected void onStop(){
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        fixHuaweiLeak();
        try {
            super.onDestroy();
            if (needButterKnife() && this.unbinder != null) {
                this.unbinder.unbind();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (needRegisterEventBus())
            EventBus.getDefault().unregister(this);
    }


    //解决华为手机内存泄漏问题
    private static Field[] leakFields = new Field[2];
    private static boolean[] hasLeakFields = {true, true};
    private static String[] leakFieldNames = {"mLastSrvView", "mNextServedView"};

    private void fixHuaweiLeak() {
        boolean goon = false;
        for (boolean has : hasLeakFields) {
            goon = goon || has;
            if (goon) break;
        }
        if (!goon) return;

        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        for (int i = 0; i < leakFieldNames.length; i++) {
            try {
                if (leakFields[i] == null) {
                    leakFields[i] = imm.getClass().getDeclaredField(leakFieldNames[i]);
                }
                if (leakFields[i] == null) {
                    hasLeakFields[i] = false;
                }
                if (leakFields[i] != null) {
                    leakFields[i].setAccessible(true);
                    leakFields[i].set(imm, null);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    public void hideSystemStatusBar() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public void hideSystemNavBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
                            // bar
                            | View.SYSTEM_UI_FLAG_IMMERSIVE);
        } else {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav
            );
        }
    }
}
