package com.hainaos.vc.base.mvvm;

import android.content.Context;

import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;

import java.lang.ref.WeakReference;

import io.reactivex.rxjava3.subjects.BehaviorSubject;

/**
 * 所有viewmodel的基类
 */
public abstract class BaseViewModel<VDB extends ViewDataBinding, T> extends ViewModel implements ViewDataBindingCallback {

    /**
     * 当前viewmodel对应的页面binding
     */
    protected VDB binding;

    @Override
    public void setVDBinding(ViewDataBinding vdBinding) {

        binding = (VDB) vdBinding;
    }

    @Override
    public VDB getVDBinding() {
        if (binding == null) {
            throw new NullPointerException("BaseViewModel >> getVDBinding >> null!!!");
        }
        return binding;
    }


    /**
     * 上下文
     */
    private WeakReference<Context> ctx;

    @Override
    public void setCtx(Context context) {
        if (ctx == null) {
            ctx = new WeakReference<>(context);
        }
    }

    @Override
    public Context getCtx() {
        if (ctx == null) {
            throw new NullPointerException("BaseViewModel >> getCtx >> null!!!");
        }
        return ctx.get();
    }


    public abstract void onDestroy();

    private BehaviorSubject<T> mBehaviorSubject;

    @Override
    public void setLifecycle(BehaviorSubject subject) {
        this.mBehaviorSubject = (BehaviorSubject<T>) subject;
    }

    @Override
    public BehaviorSubject<T> getLifecycle() {
        return mBehaviorSubject;
    }
}
