package tech.starwin.base;

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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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.mvp.IView;
import tech.starwin.utils.PresenterHoler;
import tech.starwin.widget.ProgressDialog;
import tech.starwin.utils.ui_utils.UIHelper;

/**
 * Created by SiKang on 2018/9/16.
 */
public abstract class BaseFragment extends Fragment implements IView {
    protected String TAG;
    private ViewGroup mContentView;

    /**
     * TopBar
     */
    private QMUITopBar mTopBar;

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

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

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

    Object unBinder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getName();
        lifecycleSubject.onNext(ActivityEvent.CREATE);
        presenterHelper = new PresenterHoler(this);
        progressDialog = new ProgressDialog(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (mContentView != null) {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (parent != null) {
                parent.removeView(mContentView);
            }
            unBinder = LibConfig.bindView(this, mContentView);
        } else {
            mContentView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.base_activity_root, null);
            if (useTopBar()) {
                mTopBar = LayoutInflater.from(getActivity()).inflate(R.layout.base_topbar, mContentView, true).findViewById(R.id.layout_topbar);
                if (mTopBar != null)
                    initTopBar(mTopBar);
            }
            LayoutInflater.from(getActivity()).inflate(bindLayout(), mContentView, true);
            unBinder = LibConfig.bindView(this, mContentView);
            initView(mContentView);
        }

        return mContentView;
    }

    public ViewGroup getContentView() {
        return mContentView;
    }

    @LayoutRes
    public abstract int bindLayout();

    /**
     * 初始化入口
     */
    public abstract void initView(ViewGroup contentView);

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

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


    //------------------------------------------- IView -------------------------------------------
    @Override
    public void onHttpStart(String action, boolean isShowLoading) {
        if (isShowLoading) {
            progressDialog.showLoading();
        }
    }

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


    //------------------------------------------- Lifecycle -------------------------------------------
    @Override
    public void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);
    }

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

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

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

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

    public View findViewById(@IdRes int id){
        return mContentView.findViewById(id);
    }

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


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

    public <T extends BasePresenter> T getPresenter(Class<T> clz) {
        return presenterHelper.getPresenter(clz);
    }

    public void startFragment(Fragment fragment, boolean isOpenAnime) {
        if (getActivity() instanceof BaseActivity)
            ((BaseActivity) getActivity()).startFragment(fragment, isOpenAnime);

    }

    public void startFragmentAndDestroyCurrent(Fragment fragment, boolean isOpenAnime) {
        if (getActivity() instanceof BaseActivity)
            ((BaseActivity) getActivity()).startFragmentAndDestroyCurrent(fragment, isOpenAnime);
    }
}
