package com.ttstd.dialer.activity.contact.add;

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.ttstd.dialer.base.mvvm.BaseViewModel;
import com.ttstd.dialer.databinding.ActivityContactAddBinding;
import com.ttstd.dialer.db.contact.ContactInfo;
import com.ttstd.dialer.db.contact.ContactRepository;

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

public class ContactAddViewModel extends BaseViewModel<ActivityContactAddBinding, ActivityEvent> {
    private static final String TAG = "ContactAddViewModel";
    private ContactRepository mRepository;

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

    public MutableLiveData<Long> mIntegerMutableLiveData = new MutableLiveData<>();

    public void saveContact(String name, String phone) {
        Observable.create(new ObservableOnSubscribe<Long>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Long> emitter) throws Throwable {
                int count = mRepository.getTotalCount() + 1;
                ContactInfo contactInfo = new ContactInfo(name, phone, count);
                Log.e(TAG, "saveContact: " + contactInfo);
                emitter.onNext(mRepository.insert(contactInfo));
                emitter.onComplete();
            }
        }).compose(RxLifecycle.bindUntilEvent(getLifecycle(), ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.e("saveContact", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        Log.e("saveContact", "onNext: " + aLong);
                        mIntegerMutableLiveData.setValue(aLong);
                    }

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

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

}
