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

import org.mercury_im.messenger.core.data.repository.DirectChatRepository;
import org.mercury_im.messenger.core.viewmodel.MercuryViewModel;
import org.mercury_im.messenger.entity.chat.DirectChat;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

public class ChatListViewModel implements MercuryViewModel {

    private final DirectChatRepository directChatRepository;

    private final BehaviorSubject<Observable<List<DirectChat>>> chatSourceObservable;

    @Inject
    public ChatListViewModel(DirectChatRepository directChatRepository) {
        this.directChatRepository = directChatRepository;

        chatSourceObservable = BehaviorSubject.createDefault(directChatRepository.observeAllDirectChats());
    }

    public Observable<List<DirectChat>> observeAllDirectChats() {
        return Observable.switchOnNext(chatSourceObservable);
    }

    public void onQueryTextChanged(String query) {
        if (query.trim().isEmpty()) {
            chatSourceObservable.onNext(directChatRepository.observeAllDirectChats());
        } else {
            chatSourceObservable.onNext(directChatRepository.findChatsByQuery(query));
        }
    }
}
