package tech.starwin.base;

import android.os.Bundle;
import android.support.annotation.CheckResult;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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.PresenterHoler;
import tech.starwin.utils.context_utils.FragmentLauncher;
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;

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

    private Object unBinder;

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

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

    @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) {
            progressDialog.showLoading();
        }
    }


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


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


    private void initRootLayout() {
        setContentView(R.layout.base_activity_root);
        rootLayout = findViewById(R.id.activity_base_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) {
            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;
    }

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

    public FragmentLauncher getFragmentLauncher() {
        return null;
    }

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

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

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

    /**
     * 打开一个Fragment
     */
    public void startFragment(Fragment fragment, boolean isAddToBackStack) {
        if (getFragmentLauncher() != null)
            getFragmentLauncher().startFragment(fragment, isAddToBackStack);
    }

    /**
     * 打开一个Fragment，且替换BackStack栈顶Fragment
     */
    public void startFragmentAndDestroyCurrent(final Fragment fragment) {
        if (getFragmentLauncher() != null)
            getFragmentLauncher().startFragmentAndDestroyCurrent(fragment);
    }

}
