package org.mercury_im.messenger.ui.account;

import android.app.Application;

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

import org.mercury_im.messenger.MercuryImApplication;
import org.mercury_im.messenger.Messenger;
import org.mercury_im.messenger.data.repository.AccountRepository;
import org.mercury_im.messenger.entity.Account;
import org.mercury_im.messenger.xmpp.state.ConnectionPoolState;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;

public class AccountsViewModel extends AndroidViewModel {

    @Inject
    AccountRepository repository;

    @Inject
    Messenger messenger;

    private final MutableLiveData<ConnectionPoolState> connectionPool = new MutableLiveData<>();
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Inject
    public AccountsViewModel(Application application) {
        super(application);
        MercuryImApplication.getApplication().getAppComponent().inject(this);
        compositeDisposable.add(messenger.getConnectionManager()
                .observeConnectionPool()
                .subscribe(connectionPool::postValue));
    }

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

    public CompositeDisposable getDisposable() {
        return compositeDisposable;
    }

    public LiveData<ConnectionPoolState> getConnectionPool() {
        return connectionPool;
    }

    public void setAccountEnabled(Account accountModel, boolean enabled) {
        accountModel.setEnabled(enabled);
        repository.upsertAccount(accountModel)
                .subscribe();
    }
}
