package com.ttstd.dialer.fragment.app;

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.FragmentAppBinding;
import com.ttstd.dialer.db.app.AppInfo;
import com.ttstd.dialer.db.app.AppRepository;
import com.ttstd.dialer.livedata.SingleLiveEvent;

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 AppViewModel extends BaseViewModel<FragmentAppBinding, FragmentEvent> {
    private static final String TAG = "AppViewModel";

    private AppRepository mAppRepository;

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

    public SingleLiveEvent<Integer> mAppUpdateData = new SingleLiveEvent<>();

//    public void resetLiveData() {
//        mAppUpdateData = new MutableLiveData<>();
//    }

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

                    @Override
                    public void onNext(@NonNull Integer row) {
                        Log.e("updateAppInfo", "onNext: " + row);
                        mAppUpdateData.setValue(row);
                    }

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

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