package com.ttstd.dialer.activity.main;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.trello.rxlifecycle4.RxLifecycle;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.trello.rxlifecycle4.android.FragmentEvent;
import com.ttstd.dialer.base.mvvm.BaseViewModel;
import com.ttstd.dialer.databinding.ActivityMainBinding;
import com.ttstd.dialer.db.app.AppInfo;
import com.ttstd.dialer.db.app.AppRepository;

import java.util.List;
import java.util.concurrent.Callable;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MainViewModel extends BaseViewModel<ActivityMainBinding, ActivityEvent> {
    private static final String TAG = "MainViewModel";

    private AppRepository mAppRepository;

    @Override
    public void setContext(Context context) {
        super.setContext(context);
        mAppRepository = new AppRepository(context);
    }

    public MutableLiveData<List<AppInfo>> mDesktopSortAppData = new MutableLiveData<>();

    public void getOutsideApp() {
        Observable.fromCallable(new Callable<List<AppInfo>>() {
            @Override
            public List<AppInfo> call() throws Exception {
                return mAppRepository.getOutsideApp();
            }
        }).compose(RxLifecycle.bindUntilEvent(getLifecycle(), ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AppInfo>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.e("getOutsideApp", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(@NonNull List<AppInfo> appInfos) {
                        Log.e("getOutsideApp", "onNext: " + appInfos);
                        mDesktopSortAppData.setValue(appInfos);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("getOutsideApp", "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.e("getOutsideApp", "onComplete: ");
                    }
                });
    }
}
