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

import org.bouncycastle.openpgp.PGPException;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.ikey.IkeyManager;
import org.jivesoftware.smackx.ox.OpenPgpSecretKeyBackupPassphrase;
import org.jivesoftware.smackx.pubsub.PubSubException;
import org.mercury_im.messenger.core.connection.MercuryConnection;
import org.mercury_im.messenger.core.connection.MercuryConnectionManager;
import org.mercury_im.messenger.core.crypto.ikey.IkeyInitializer;
import org.mercury_im.messenger.core.crypto.ikey.IkeyRepository;
import org.mercury_im.messenger.core.util.Optional;
import org.mercury_im.messenger.core.viewmodel.MercuryViewModel;
import org.mercury_im.messenger.entity.Account;

import java.io.IOException;
import java.util.UUID;

import javax.inject.Inject;

import io.reactivex.Completable;
import io.reactivex.Observable;

public class IkeySecretKeyBackupCreationViewModel implements MercuryViewModel {

    private final MercuryConnectionManager connectionManager;
    private final IkeyInitializer ikeyInitializer;
    private UUID accountId;
    private final IkeyRepository ikeyRepository;

    @Inject
    public IkeySecretKeyBackupCreationViewModel(MercuryConnectionManager connectionManager, IkeyInitializer ikeyInitializer, IkeyRepository ikeyRepository) {
        this.connectionManager = connectionManager;
        this.ikeyInitializer = ikeyInitializer;
        this.ikeyRepository = ikeyRepository;
    }

    public void setAccountId(UUID accountId) {
        this.accountId = accountId;
    }

    public Observable<Optional<OpenPgpSecretKeyBackupPassphrase>> getPassphrase() {
        return ikeyRepository.loadBackupPassphrase(accountId).toObservable();
    }

    public void doCreateBackup() throws XMPPException.XMPPErrorException, InterruptedException,
            SmackException.NoResponseException, SmackException.NotConnectedException,
            SmackException.FeatureNotSupportedException, PGPException,
            PubSubException.NotALeafNodeException, IOException {
        MercuryConnection connection = connectionManager.getConnection(accountId);
        IkeyManager ikeyManager = ikeyInitializer.initFor(connection);

        ikeyManager.depositIdentityKeyBackup();
    }

    public Completable createBackup() {
        return Completable.fromAction(this::doCreateBackup);
    }
}
