package com.hc.viewmodel;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

public class BaseViewModel extends AndroidViewModel {

    /**
     * 是否显示正在加载中UI
     */
    private final SingleBooleanEvent singleBooleanEvent = new SingleBooleanEvent();
    /**
     * 是否得到空数据
     */
    private final SingleBooleanEvent emptyDataEvent = new SingleBooleanEvent();
    /**
     * 是否获取数据失败
     */
    private final SingleBooleanEvent invalidDataEvent = new SingleBooleanEvent();

    BaseViewModel(@NonNull Application application) {
        super(application);
    }

    public SingleBooleanEvent getSingleBooleanEvent() {
        return singleBooleanEvent;
    }

    public SingleBooleanEvent getInvalidDataEvent() {
        return invalidDataEvent;
    }

    public SingleBooleanEvent getEmptyDataEvent() {
        return emptyDataEvent;
    }

    public static <T extends BaseViewModel> T obtainViewModel(FragmentActivity activity, Class<T> clz) {
        ViewModelInstance factory = ViewModelInstance.getInstance(activity.getApplication());
        return ViewModelProviders.of(activity, factory).get(clz);
    }

    @Nullable
    public static <T extends BaseViewModel> T obtainViewModel(Fragment fragment, Class<T> clz) {
        if(fragment.getActivity() == null) {
            return null;
        }
        ViewModelInstance factory = ViewModelInstance.getInstance(fragment.getActivity().getApplication());
        return ViewModelProviders.of(fragment, factory).get(clz);
    }
}
