package tech.starwin.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.CheckResult;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.firebase.messaging.RemoteMessage;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;
import tech.starwin.LibConfig;
import tech.starwin.R;
import tech.starwin.service.MsgHandleService;
import tech.starwin.mvp.IView;
import tech.starwin.utils.context_utils.AppLanguageUtils;
import tech.starwin.utils.PresenterHoler;
import tech.starwin.utils.context_utils.FragmentLauncher;
import tech.starwin.utils.ui_utils.DialogFactory;
import tech.starwin.widget.ProgressDialog;

/**
 * Created by SiKang on 2018/9/14.
 */
public abstract class BaseActivity extends AppCompatActivity implements IView {
    public String TAG;
    /**
     * 根布局
     */
    public ViewGroup rootLayout;

    /**
     * TopBar
     */
    private QMUITopBar mTopBar;

    /**
     * 创建和缓存Presenter实例
     */
    private PresenterHoler presenterHelper;

    /**
     * 侧滑抽屉
     */
    private DrawerLayout drawerLayout;

    /**
     * loading、error 提示
     */
    protected ProgressDialog progressDialog;

    private FragmentLauncher fragmentLauncher;


    private Object unBinder;

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();


    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(AppLanguageUtils.attachBaseContext(newBase, LibConfig.LANGUAGE));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();
        lifecycleSubject.onNext(ActivityEvent.CREATE);
        progressDialog = new ProgressDialog(this);
        presenterHelper = new PresenterHoler(this);
        initRootLayout();

    }

    @Override
    protected void onStart() {
        super.onStart();
        //如果是通过FireBase CloudMessage 调起的界面，将消息交给Service处理
        String action = getIntent().getAction() == null ? "" : getIntent().getAction();
        String from = getIntent().getStringExtra("from");
        if (action.equals("android.intent.action.MAIN") &&
                !TextUtils.isEmpty(from)) {
            MsgHandleService.handleMsg(this, new RemoteMessage(getIntent().getExtras()));
        }
        lifecycleSubject.onNext(ActivityEvent.START);
    }

    public ViewGroup getContentView() {
        return rootLayout;
    }

    @Override
    protected void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
    }

    @Override
    protected void onPause() {
        super.onPause();
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        progressDialog.dissmissLoading();
    }

    @Override
    protected void onStop() {
        super.onStop();
        lifecycleSubject.onNext(ActivityEvent.STOP);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unBinder != null) {
            LibConfig.unBindView(unBinder);
        }
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        presenterHelper.onDestory();
    }

    @Override
    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }


    //-----------------------------------  IView  ----------------------------------------


    @Override
    public void onHttpStart(String action, boolean isShowLoading) {
        if (isShowLoading) {
            //500ms后如果还没有收到返回数据，显示loading
            progressDialog.setEnable(true);
            rootLayout.postDelayed(() -> progressDialog.showLoading(), 500);
        }
    }


    @Override
    public void onHttpFinish(String action) {
        progressDialog.setEnable(false);
        progressDialog.dissmissLoading();
    }

    @Override
    public void onHttpError(String action, String msg) {
        DialogFactory.createMessageDialog(this, "Tip", msg, "OK").show();
    }

    //-----------------------------------  Layout  ----------------------------------------

    private void initRootLayout() {
        setContentView(R.layout.base_activity_root);
        rootLayout = findViewById(R.id.root_layout);
        //判断是否要显示TopBar
        if (useTopBar()) {
            mTopBar = LayoutInflater.from(this).inflate(R.layout.base_topbar, rootLayout, true).findViewById(R.id.layout_topbar);
            if (mTopBar != null)
                initTopBar(mTopBar);
        }
        //填充Activity -> bindLayout();
        if (bindLayout() != 0) {
            //是否使用了侧滑
            if (bindDrawerLayout() != 0) {
                drawerLayout = LayoutInflater.from(this).inflate(R.layout.base_activity_drawer, rootLayout, true).findViewById(R.id.root_drawer_layout);
                FrameLayout content = drawerLayout.findViewById(R.id.root_content);
                FrameLayout drawer = drawerLayout.findViewById(R.id.root_drawer);
                drawer.setClickable(true);
                LayoutInflater.from(this).inflate(bindLayout(), content, true);
                LayoutInflater.from(this).inflate(bindDrawerLayout(), drawer, true);
            } else {
                LayoutInflater.from(this).inflate(bindLayout(), rootLayout, true);
            }

            unBinder = LibConfig.bindView(this, rootLayout);
            initView();
        } else {
            throw new RuntimeException("找不到布局文件 bindLayout() -> " + bindLayout());
        }
    }

    /**
     * 绑定布局文件
     */
    @LayoutRes
    public abstract int bindLayout();

    /**
     * Activity初始化
     */
    public abstract void initView();

    /**
     * 是否使用TopBar，默认使用
     */
    public boolean useTopBar() {
        return true;
    }

    /**
     * 是否使用侧滑
     */
    public int bindDrawerLayout() {
        return 0;
    }

    /**
     * 初始化TopBar，需要自定义TopBar样式时重写
     * 默认TopBar只包含一个BackButton 和 Titile
     */
    protected void initTopBar(QMUITopBar topBar) {
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void setTopBarTitle(String title) {
        if (title != null && mTopBar != null) {
            mTopBar.setTitle(title);
        }
    }

    @IdRes
    public int bindFragmentLayout() {
        return 0;
    }

    public FragmentLauncher getFragmentLauncher() {
        if (bindFragmentLayout() != 0 && fragmentLauncher == null) {
            fragmentLauncher = new FragmentLauncher(this, bindFragmentLayout());
        }
        return fragmentLauncher;
    }

    public boolean isDrawerOpen() {
        return drawerLayout.isDrawerOpen(Gravity.LEFT);
    }

    public void openDrawer() {
        if (drawerLayout != null && !drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    public void closeDrawer() {
        if (drawerLayout != null && drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.closeDrawer(Gravity.LEFT);
        }
    }

//-----------------------------------  Presenter  ----------------------------------------

    /**
     * 获取Presenter
     */
    public <T extends BasePresenter> T getPresenter(Class<T> clz) {
        return presenterHelper.getPresenter(clz);
    }

    //-----------------------------------  Fragment  ----------------------------------------

    /**
     * 打开一个Fragment
     */
    public void startFragment(Fragment fragment, boolean isOpenAnime) {
        if (getFragmentLauncher() != null) {
            FragmentLauncher.TransitionConfig config = null;
            if (isOpenAnime) {
                config = new FragmentLauncher.TransitionConfig(
                        R.anim.slide_open_enter, R.anim.slide_open_exit,
                        R.anim.slide_close_enter, R.anim.slide_close_exit);

            }
            getFragmentLauncher().startFragment(fragment, config, isOpenAnime);
        }
    }

    /**
     * 打开一个Fragment，且替换BackStack栈顶Fragment
     */
    public void startFragmentAndDestroyCurrent(final Fragment fragment, boolean isOpenAnime) {
        if (getFragmentLauncher() != null) {
            FragmentLauncher.TransitionConfig config = null;
            if (isOpenAnime) {
                config = new FragmentLauncher.TransitionConfig(
                        R.anim.slide_open_enter, R.anim.slide_open_exit,
                        R.anim.slide_close_enter, R.anim.slide_close_exit);

            }
            getFragmentLauncher().startFragmentAndDestroyCurrent(fragment, config);
        }
    }

}
