package org.mercury_im.messenger.android.ui.chatlist;

import android.app.Application;

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

import org.mercury_im.messenger.android.MercuryImApplication;
import org.mercury_im.messenger.android.ui.MercuryAndroidViewModel;
import org.mercury_im.messenger.core.SchedulersFacade;
import org.mercury_im.messenger.core.data.repository.DirectChatRepository;
import org.mercury_im.messenger.core.viewmodel.chat.ChatListViewModel;
import org.mercury_im.messenger.entity.chat.DirectChat;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;

public class AndroidChatListViewModel extends AndroidViewModel implements MercuryAndroidViewModel<ChatListViewModel> {

    @Inject
    DirectChatRepository chatRepository;

    @Inject
    ChatListViewModel commonViewModel;

    @Inject
    SchedulersFacade schedulers;

    private final MutableLiveData<List<DirectChat>> chats = new MutableLiveData<>(new ArrayList<>());

    public AndroidChatListViewModel(@NonNull Application application) {
        super(application);
        ((MercuryImApplication) application).getAppComponent().inject(this);

        addDisposable(commonViewModel.observeAllDirectChats()
                .compose(schedulers.executeUiSafeObservable())
                .subscribe(chats::setValue));
    }

    public LiveData<List<DirectChat>> getChats() {
        return chats;
    }

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

    public void onQueryTextChanged(String query) {
        getCommonViewModel().onQueryTextChanged(query);
    }
}
