package com.ttstd.controller.activity.splash;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.ttstd.controller.base.mvvm.BaseViewModel;
import com.ttstd.controller.network.AuthRepository;

import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.schedulers.Schedulers;

import java.util.concurrent.TimeUnit;

/**
 * 启动页 ViewModel：校验本地登录态，决定跳转登录页还是主页。
 */
public class SplashViewModel extends BaseViewModel {

    /** 最短停留时长，避免闪屏一闪而过。 */
    private static final long MIN_SPLASH_MILLIS = 800L;

    private final AuthRepository repository = new AuthRepository();

    /** true=已登录进主页，false=去登录页。 */
    private final MutableLiveData<Boolean> loggedIn = new MutableLiveData<>();

    public LiveData<Boolean> getLoggedIn() {
        return loggedIn;
    }

    /**
     * 校验登录态。请求由 BaseViewModel 的 CompositeDisposable 托管，
     * 页面销毁时自动取消，不会产生野线程回调。
     */
    public void checkLoginState() {
        execute(
                Single.zip(
                        repository.checkLoginState(),
                        Single.timer(MIN_SPLASH_MILLIS, TimeUnit.MILLISECONDS, Schedulers.io()),
                        (valid, ignored) -> valid),
                loggedIn::setValue,
                error -> loggedIn.setValue(false));
    }
}
