package org.mercury_im.messenger.core.crypto.ikey;

import org.jivesoftware.smackx.ikey.IkeyManager;
import org.mercury_im.messenger.core.SchedulersFacade;
import org.mercury_im.messenger.core.connection.MercuryConnection;

import javax.inject.Inject;

public class IkeyInitializer {

    private final IkeyRepository ikeyRepository;
    private final SchedulersFacade schedulers;

    @Inject
    public IkeyInitializer(IkeyRepository ikeyRepository, SchedulersFacade schedulers) {
        this.ikeyRepository = ikeyRepository;
        this.schedulers = schedulers;
    }

    public IkeyManager initFor(MercuryConnection connection) {
        IkeyManager ikeyManager = IkeyManager.getInstanceFor(connection.getConnection());
        if (ikeyManager.hasStore()) {
            return ikeyManager;
        }
        ikeyManager.startListeners();

        // bind repo to store
        IkeyStoreAdapter store = new IkeyStoreAdapter(connection.getAccountId(), ikeyRepository, schedulers);
        ikeyManager.setStore(store);

        return ikeyManager;
    }
}
