package org.mercury_im.messenger.android.ui.roster.contacts;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import org.mercury_im.messenger.android.MercuryImApplication;
import org.mercury_im.messenger.android.ui.MercuryAndroidViewModel;
import org.mercury_im.messenger.core.Messenger;
import org.mercury_im.messenger.core.viewmodel.roster.ContactListViewModel;
import org.mercury_im.messenger.entity.Account;
import org.mercury_im.messenger.entity.contact.Peer;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;
import lombok.Getter;


public class AndroidContactListViewModel extends AndroidViewModel
        implements MercuryAndroidViewModel<ContactListViewModel> {

    @Inject
    ContactListViewModel commonViewModel;

    @Inject
    @Getter
    Messenger messenger;

    private final MutableLiveData<List<Peer>> rosterEntryList = new MutableLiveData<>();
    private final MutableLiveData<List<Account>> accounts = new MutableLiveData<>();
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();

    public AndroidContactListViewModel(@NonNull Application application) {
        super(application);
        ((MercuryImApplication) application).getAppComponent().inject(this);
        // Subscribe to changes to the contacts table and update the LiveData object for the UI.
        compositeDisposable.add(getCommonViewModel().getContacts()
                .subscribe(rosterEntryList::postValue));
        compositeDisposable.add(getCommonViewModel().getAccounts()
                .subscribe(accounts::postValue));
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        compositeDisposable.clear();
    }

    public LiveData<List<Peer>> getRosterEntryList() {
        return rosterEntryList;
    }

    public LiveData<List<Account>> getAccounts() {
        return accounts;
    }

    public void onContactSearchQueryTextChanged(String query) {
        getCommonViewModel().onContactSearchQueryChanged(query);
    }

    @Override
    public ContactListViewModel getCommonViewModel() {
        return commonViewModel;
    }
}
