package com.ttstd.dialer.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;

public abstract class BaseViewModel<VDB extends ViewDataBinding, T> extends ViewModel {

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

    public void setVDBinding(ViewDataBinding vdBinding) {
        binding = (VDB) vdBinding;
    }

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

    private WeakReference<Context> weakContext;

    public void setContext(Context context) {
        if (weakContext == null) {
            weakContext = new WeakReference<>(context.getApplicationContext());
        }
    }

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

    private BehaviorSubject<T> mBehaviorSubject;

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

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