package org.mercury_im.messenger.core.viewmodel.roster;

import org.mercury_im.messenger.core.data.repository.AccountRepository;
import org.mercury_im.messenger.core.data.repository.PeerRepository;
import org.mercury_im.messenger.core.viewmodel.MercuryViewModel;
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.Observable;
import io.reactivex.subjects.BehaviorSubject;
import lombok.Getter;

public class ContactListViewModel implements MercuryViewModel {

    private final PeerRepository peerRepository;
    private final AccountRepository accountRepository;

    @Getter
    private Observable<List<Peer>> contacts;

    @Getter
    private Observable<List<Account>> accounts;

    private BehaviorSubject<Observable<List<Peer>>> queryResultObservables = BehaviorSubject.create();

    @Inject
    public ContactListViewModel(PeerRepository peerRepository, AccountRepository accountRepository) {
        this.peerRepository = peerRepository;
        this.accountRepository = accountRepository;

        queryResultObservables.onNext(peerRepository.observeAllPeers());
        this.contacts = Observable.switchOnNext(queryResultObservables);
        this.accounts = accountRepository.observeAllAccounts();
    }

    public void onContactSearchQueryChanged(String query) {
        if (query.trim().isEmpty()) {
            queryResultObservables.onNext(peerRepository.observeAllPeers());
        } else {
            queryResultObservables.onNext(peerRepository.findPeers(query));
        }
    }
}
