package org.mercury_im.messenger;

import org.mercury_im.messenger.data.repository.Repositories;
import org.mercury_im.messenger.entity.Account;
import org.mercury_im.messenger.xmpp.MercuryConnectionManager;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

@Singleton
public class Messenger {

    public static final String TAG = "MercuryIM";
    private static final Logger LOGGER = Logger.getLogger(Messenger.class.getName());

    private final MercuryConnectionManager connectionManager;
    private final Repositories repositories;

    private CompositeDisposable disposable = new CompositeDisposable();

    @Inject
    public Messenger(Repositories repositories, MercuryConnectionManager connectionManager) {
        this.repositories = repositories;
        this.connectionManager = connectionManager;
        performInitialLogin();
    }

    public MercuryConnectionManager getConnectionManager() {
        return connectionManager;
    }

    public void performInitialLogin() {
        LOGGER.log(Level.INFO, "Perform initial login.");
        disposable.add(repositories.getAccountRepository().observeAllAccounts().firstOrError()
                .subscribeOn(Schedulers.newThread())
                .subscribe(connectionManager::registerConnections));
    }

    public Account createAccount(String username, String service, String password) {
        Account account = new Account();
        account.setAddress(username + "@" + service);
        account.setPassword(password);
        return account;
    }

}
